Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 220
Joseph Nields Avatar asked Sep 04 '25 17:09

Joseph Nields


1 Answers

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
like image 82
haim770 Avatar answered Sep 07 '25 18:09

haim770