Consider the following code, simply a class with a custom widening conversion from Long (Int64).
Public Class CharacterArgs
Private _CharacterID As Long
Public ReadOnly Property CharacterID() As Long
Get
Return _CharacterID
End Get
End Property
Public Sub New(ByVal characterID As Long)
_CharacterID = characterID
End Sub
Public Sub New()
End Sub
Overloads Shared Widening Operator CType(ByVal source As Long) As CharacterArgs
Return New CharacterArgs(source)
End Operator
End Class
The following code works:
Dim test As CharacterArgs
test = 10
But:
Dim canAssign = GetType(CharacterArgs).IsAssignableFrom(GetType(Long)) 'False
Dim convertTest = Convert.ChangeType(10L, GetType(CharacterArgs))
'Throws InvalidCastException
So my questions:
System.Type object (as opposed to CType)?IsAssignableFrom, that will account for the custom conversion as well?So far as I know, neither of the things you are looking for exist. The closest I can think of for the first requirement would be a TypeConverter. However, TypeConverters seem geared toward designer support and are specific to a single type that will always be either the source or destination type.
To find the conversion methods on a type, you could make a function to look for methods with the special names op_Implicit and op_Explicit (as per MSDN) on either the source or destination types with the appropriate arguments and return types.
As an aside, the reason IsAssignableFrom returns false in this case is that it checks if one type can be assigned a variable of another type directly without conversions. Conversion operators add confusion to this issue because in the source code it appears that you are doing a simple assignment, but you are actually calling a method and assigning its result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With