Rono Rono - 1 year ago 97 Question

In VB.Net using an anonymous object type to create a generic class object

I have a function that accepts a parameter of type object which is an anonymous type generated elsewhere. I also have a generic class which I am trying to create an instance of using that anonymous type as the type passed to the generic class. But I am unable to get this to work.

So here is basically what I have for my generic class:

Class Foo(Of T)
End Class

So in my function I have something like this:

Public Sub MyFunction(data As Object)
'data is an anonymous Type

dim item = new Foo(Of ??)
End Sub

I can't figure out what to give to the new Foo line to get this to work. One thing I tried was to create a constructor on Foo which accepts a parameter of type T, so that the type is inferred from that, but that gives me this compile error when I call the constructor:

Too few type arguments to 'Foo(Of T)'

How do I get this to work so that the generic class accepts the anonymous type?

Answer Source

Change MyFunction data from object to T.

Public Sub MyFunction(Of T)(data As T)
    Dim item = New Foo(Of T)()
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download