Ccorock
Ccorock

Reputation: 892

Passing type argument to a generic custom class

I've seen a lot of chatter on this topic. Though the examples and desired outcomes are always very specific and specialized. Any direction on this is appreciated.

Custom Class:

Public Class customClass(Of T, S)
[include properties]
[include methods]
End Class

Implementation of Class:

dim [string] as string = string.empty
dim [type] as type = [string].gettype 

dim instance as customClass(of [type], integer) 

Also note, I've read that vb.net does not allow you to pass parameters to its constructor. I refuse to accept that you can't pass a type to a class and generate objects dependent on the type of that argument. Is the only answer to this a function in the class which returns a list of objects cast to the desired type? Your time is appreciated.

This question is motivated by academic research. The above is "what I am trying to do" thanks.

Upvotes: 0

Views: 4090

Answers (2)

Ivan Ferrer Villa
Ivan Ferrer Villa

Reputation: 2158

You cannot use dynamic types to call this kind of typed declarations (Of t,s) but you can 'group' or delimit several types using interfaces or inheritance, which could also be very useful.

Class customClass(Of T As iMyInterface, s As iMyInterface)
End Class

Interface iMyInterface
End Interface

Class MyClass1
    Implements iMyInterface
End Class
Class MyClass2
    Implements iMyInterface
End Class

Dim y As New customClass(Of MyClass1, MyClass2)

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40393

Kind of hard to see what you're trying to do, but if I'm reading this right, you're trying to take a variable and use that as the generic argument. This is not possible in .NET - when you declare a variable of a generic class, you need a compile-time type as the generic argument, so it cannot be the a variable of type Type.

This is important for a couple of reasons, one of which is to ensure that type constraints are met.

So:

Class Foo(Of T)
End Class

Dim x as Type = GetType(String)
Dim y as Foo(Of x)

does not work - you have to do:

Dim y as Foo(Of String)

There's always reflection and expression trees, but that's more of a hack than a solution.

Upvotes: 2

Related Questions