Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I would like to have a collection (e.g. List or Dictionary, or even an array) of Generic objects. For example, imagine I've defined a generic class 'Pair' that takes any two things. In order to create a List of Pair objects, I'd have to define it like this:

dim objList as List(Of Pair(Of String, Integer))

Unfortunately, this means that every item in the list can only be an instance of Pair(String, Integer), and thus I'm not able to take full advantage of the generics paradigm as I understand it.

I know I could create a more general superclass from which Pair inherits, but I don't want the list to contain just any object that inherits from the superclass; I want it to contain Pair objects and Pair objects alone.

Is there any way that this can be done?
Posted
Updated 15-Dec-09 3:02am
v2

I don't think you can have a generic collection of generic types. A generic class/collection requires an actual type when you declare it. So, if you declare a List and use a generic type in the definition, you need to declare the generic type with an actual type. I don't think there is any way around this.

As far as what you are trying to do, you could to create a class that uses objects to represent the pairs of values, and determine the types using reflection as runtime.
 
Share this answer
 
Technically, generics -are- just "any class". They arent actually related to each other in an Object Oriented sense at all. Its very similar to generating a series of classes using snippets; you wouldn't expect them to think they are related (although with reflection you *can* determine the generic template common to your Pair class, it's still just runtime avaliable 'documentation' rather than OO).

So there is no actual Pair type or class in your code. You do have to create a superclass / interface if you want the specific classes (Pair<string,>, Pair<usercontrol,> etc.) to be related, and you have to use a List(Of IPair) instead.

However this is where I disagree with pretty much every other post I've seen on this issue: dont use reflection to get the type parameter at runtime. What you do is have every method that needs knowledge of the type parameters on the Pair class itself. These methods might have just one line calling a generic method on another class. So long as you remember that if you need a process to know about the type parameter, you start it on the generic itself.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900