lsteinme
lsteinme

Reputation: 750

How to convert an Integer automatically to my type?

What I want to do is the following:

class myNumber
    sub new(i as integer)
    end sub
end class

sub main()
    Dim listl as new List(of myNumber)
     listl.add(1)
     ' some more stuff ... '
end sub

so the question is what kind of function do I have to override, or what attribute do I need to add, so that the code in main compiles?

Its not for any specific purpose, just curiosity.

Upvotes: 0

Views: 47

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460058

You need to provide an implicit conversion from System.Int32 to MyNumber. In this case i would also use a Structure instead of a class since it represents an immutable value type.

In VB.NET you have to override the Widening CType operator to create an implicit conversion:

Public Structure MyNumber

    Public Sub New(value As Int32)
        Me.Value = value
    End Sub

    Public Property Value As System.Int32

    Public Overloads Shared Widening Operator CType(value As Int32) As MyNumber
        Return New MyNumber(value)
    End Operator

End Structure

Now this works:

Dim listl as new List(of MyNumber)
listl.Add(1)

Upvotes: 3

Matt Wilko
Matt Wilko

Reputation: 27322

You just need to change your Add slightly to create a new instance of myNumber passing in the required integer value in the constructor:

Class myNumber
    Sub New(i As Integer)

    End Sub
End Class

Sub Main()
    Dim listl As New List(Of myNumber)
    listl.Add(New myNumber(1))
    'some more stuff
End Sub

Upvotes: 1

Related Questions