Andy-Kiev
Andy-Kiev

Reputation: 33

How to declare a variable as given Type in vb.net

Please help me to resolve this little task: how to declare a variable as given type. In this case - interface.

I guess, the answer is simple, but I don't know it, and Google don't too. I tried everything, but I can't resolve it.

Thank you.


Public Interface IMyInterface
        Property MyProperty
End Interface

    Public Sub MySimpleSub()
        Dim tType As System.Type = GetType(IMyInterface)
        Call SubAcceptsInterface(tType)
    End Sub

    Public Sub SubAcceptsInterface(ByVal tType As System.Type)
        Dim arrMyArray() As tType= {} ' <-- here's an error: Error 1 Type 'tType' is not defined.
    End Sub

Upvotes: 1

Views: 265

Answers (1)

Sideways
Sideways

Reputation: 286

If you want to pass a type of a class/structure/interface to a function, you can template the function like this:

Public Sub SubAcceptsInterface(Of tType)()
    Dim arrMyArray() As tType = {} 'This should declare fine
End Sub

Pass the tType parameter of the template like this:

Public Sub MySimpleSub()
    SubAcceptsInterface(Of IMyInterface)()
End Sub

Upvotes: 1

Related Questions