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....
Edit: I found my answer in the MSDN documentation for the Widening operator statement. 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 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
If anyone has any insight on this I would greatly appreciate it.
I think I've implemented this incorrectly now that I understand the meaning of the Widening and Narrowing operators. I have implemented it correctly. I shouldn't have doubted myself.
Thanks,
-Frinny