Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting, Assignability and custom conversions

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:

  1. Is there a casting/conversion method that supports the custom conversion, but also accepts the destination type as a System.Type object (as opposed to CType)?
  2. Is there a reflection or casting "test" method, similar to IsAssignableFrom, that will account for the custom conversion as well?
like image 793
M.A. Hanin Avatar asked Dec 11 '25 19:12

M.A. Hanin


1 Answers

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.

like image 56
Gideon Engelberth Avatar answered Dec 13 '25 12:12

Gideon Engelberth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!