Is there a way to define an implicit conversion operator in VB.NET?

.net, vb.net

Solution

In VB.NET, use the Widening CType operator to create an implicit conversion:

Class C1
    Public Shared Widening Operator CType(ByVal p1 As C1) As C2

    End Operator
End Class

The opposite, an explicit conversion, can be done by swapping `Narrowing` for `Widening` in the above definition.

Problem

In C#, you can use the implicit keyword to define an implicit user-defined type conversion operator. In VB.NET, you can define a CType conversion operator that will explicitly convert a user-defined type into another type. Is there a way to declare an implicit conversion operator in VB.NET? I can't seem to find any information on this.... Answer I found my answer in the MSDN documentation for the `Widening` operator. Apparently the CType `Widening` operator is "called" for implicit conversions whereas the CType `Narrowing` operator is called for explicit conversions. At first, I thought this documentation was incorrect, because I was experiencing an exception during testing. I re-tested and found something very strange. The function I implemented as the widening conversion operator works fine when an implicit cast is done using the "=" operator. For example, the following will implicitly cast the `Something` type into `MyClass`. It calls my `Widening` conversion implementation correctly and everything works without error: ``` Dim y As Something Dim x As MyClass = y ``` However, if the implicit cast is done in a `foreach` loop, it does not work. For example, the following code will throw an exception ("Unable to cast object of type 'Something' to type 'MyClass'") when the `Something` type is implicitly casted to `MyClass` in the `For Each` loop: ``` Dim anArrayOfSomethingTypes() As Something = getArrayOfSomethings() For Each x As MyType In anArrayOfSomethingTypes .... Next ``` Any insight on this is greatly appreciated.

Original source