ElektroStudios ElektroStudios - 4 years ago 163
Vb.net Question

How to solve: Conversion operators cannot convert from an interface type

I've wrapped the INetFwRule members, I've put the properties in a custom type named

FirewallRule
, and for elegancy to save time in other parts of the code when performing conversions from
INetFwRule
to
FirewallRule
I tried to write this implicit converter:

C#:

public static explicit operator FirewallRule(INetFwRule rule) {
return new FirewallRule {
Action = (FirewallRuleAction)rule.Action,
ApplicationName = rule.ApplicationName,
Description = rule.Description,
// etc...
};
}


Vb.Net (original):

Public Shared Narrowing Operator CType(ByVal rule As INetFwRule) As FirewallRule

Return New FirewallRule With {
.Action = DirectCast(rule.Action, FirewallRuleAction),
.ApplicationName = rule.ApplicationName,
.Description = rule.Description,
' etc ...
}

End Operator


However, I get this error in the
rule
parameter:


Conversion operators cannot convert from an interface type


There is an approach to solve this to be able write the
CType
?.

Answer Source

Compiler prohibits you from defining conversion operators that take interfaces as parameters, because it considers such conversion already defined (i.e. the built-in ability to cast).

You would need to use some other syntax to initiate conversions of INetFwRule to FirewallRule - for example, an extension to INetFwRule:

public static class NetFwRuleExt {
    public static FirewallRule ToFirewallRule(this INetFwRule rule) {
        return new FirewallRule {
            Action = (FirewallRuleAction)rule.Action,
            ApplicationName = rule.ApplicationName,
            Description = rule.Description,
            // etc...
        };
    }
}

Instead of writing

FirewallRule newRule = (FirewallRule)someRule;

clients of your API would write

FirewallRule newRule = someRule.ToFirewallRule();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download