Pierre
Pierre

Reputation: 1046

VB.NET and polymorphism

Is there a way to make VB.NET functions polymorph, when it comes to lists? The following code gives me a "invalid cast" error:

Sub TestBase()
    Dim a#()
    a = VEC.New_(42, 51, 2, 3, 4, 5) 'never mind, this just creates a non-empty list
    'at this point, a is a double()
    ARR.append(a, 5)
End Sub
Public Sub append(ByRef v, Val)
    ReDim Preserve v(0 To UBound(v) + 1) 'this line casts v into a object()
    v(UBound(v)) = Val
End Sub

Is there a correct way of doing this, apart from the fastiduous way of making one function per type?

Upvotes: 1

Views: 171

Answers (2)

Mr47
Mr47

Reputation: 2655

As rory.ap mentions, you should really be using lists.

That said, your issue can be solved by using generics like below:

public sub append(of T)(byref v() as T, Val as T)
        ReDim Preserve v(0 To UBound(v) + 1) 
        v(UBound(v)) = Val
end sub

Upvotes: 0

rory.ap
rory.ap

Reputation: 35260

First of all, I would use another type of collection, like List(Of T) rather than an array since they're much easier to work with.

Then you can just do this:

Dim a As New List(Of Double)
a.Add(5)

Upvotes: 3

Related Questions