Joseph Nields
Joseph Nields

Reputation: 5661

How to determine type in generic class VB.NET

Let's say I have a class like this:

Public Class(Of T As Bar) Foo
...
End Class

I'd like to set up something like the following:

Public Class(Of T As Bar) Foo
    Public Sub New()
        Select T
        Case Class1 'Inherits Bar
            'do stuff
        Case Class2 'Inherits Bar
            'do stuff
        Case Class3 'Inherits Bar
            'do stuff
        End Select
    End Sub
End Class

Obviously this won't work, but you can probably get the idea of what I'm trying to do from this snippet. So how do you properly determine the Type passed to the constructor in VB.NET? Surprisingly I can't find anything on Stack Overflow about this yet.

C# has the following syntax:

Type typeParameterType = typeof(T);

However,

Dim typeParameterType As Type = TypeOf T

does not work, nor does

Dim typeParameterType As Type = T

Upvotes: 4

Views: 2397

Answers (2)

supercat
supercat

Reputation: 81115

The most efficient way I've found to do this is to have a delegate as a static (shared) member of the generic class which is assigned in a static constructor. Something like:

Public Class Foo(Of T As Bar)
    Shared DoStuff As Action(of T) = AddressOf NormalDoStuff
    Shared Sub New()
      Foo(Of Class1).DoStuff = AddressOf Class1DoStuff
      Foo(Of Class2).DoStuff = AddressOf Class2DoStuff
      Foo(Of Class3).DoStuff = AddressOf Class3DoStuff
    End Sub

    Public Sub New(SomeParameter As T)
        DoStuff(SomeParameter)
    End Sub
End Class

This approach will need to do some extra work the first time an attempt is made to use a class with a particular generic type, but after that DoStuff will correctly dispatch directly to the proper method. If there are multiple spots in the code whose behavior needs to vary in different classes, simply define more static (shared) delegates.

Upvotes: 1

haim770
haim770

Reputation: 49095

C# doesn't allow switch on typeof. VB, however, does allow it so you can try something like this:

Public Class Foo(Of T As Bar)
    Public Sub New()
        Select Case GetType(T)
            Case GetType(BarA)
                ' Do stuff

            Case GetType(BarB)
                ' Do stuff
        End Select
    End Sub
End Class

Upvotes: 4

Related Questions