Reputation: 3844
i have a sub with this signature
Public Sub Save(ByVal obj As IPta)
now i want the create a instance of Generic.PtaDao(of T) with the type of obj, which could be anything that inherits from my base class Pta
how can i do that? i already found a c# example Declare a generic type instance dynamically
but i dont understand how to implement this in my case.
tia
-edit-
to clearify
lets pretend obj is a object of type Address (Address inherits from Pta so it implements IPta)
now i want to create a new PtaDao object that takes Address objects for example
Dim AddressDao as New Generic.PtaDao(of Address)
but i want to do this dynamically so if obj is of type UserGroup it should create a PtaDao(of UserGroup)
Upvotes: 2
Views: 2581
Reputation: 6621
This is not an answer, but just some advice...
Look carefully at why you're doing this. I have been in a similar situation where I used lots of reflection to create generic objects and call generic methods using types that were not known until runtime.
The result was slow to run and ugly to look at for maintenance. I ended up realising it would have been better to make the whole thing just pass Object instances around, and perform the occasional type cast.
This may not be the case for you (for example, if the generic class is from an external library that you have no control over, or if this use is a one-off), but it's worth standing back and taking a look.
Upvotes: 1
Reputation: 667
If you have access to the source of the Save method, make it generic:
Public Sub Save(Of TSomeIPtaType As {IPta, New})(ByVal obj As TSomeIPtaType)
Dim dao As New Generic.PtaDAO(Of TSomeIPtaType)
End Sub
Public Sub ExampleUsage()
Dim address As New Address
Save(address)
End Sub
Upvotes: 1
Reputation: 1499790
Make it a generic method, taking an instance of the type parameter as one of the parameters, and constrain the type parameter to have a public parameterless constructor and to implement IPta:
Public Sub Save(Of T As { IPta, New })(ByVal obj As T)
Dim foo As New T
' Do more stuff here
End Sub
Upvotes: 4