tags:

views:

65

answers:

5

Maybe a stupid question but when I have an abstract generic class, say A<T>, and I want to build a dictionary with the abstract class as value and some other type as key in a completely different class. How do I do that without specifying the type?

Dictionary<int, A<T>> dictionary doesn't compile of course.

+3  A: 

2 possibilities, I would think:

  • Make the class that hosts the dictionary generic as well and let the type argument "trickle through"
  • Find a non-generic interface under which you can store the instances in the dictionary.
flq
+3  A: 

You can only do this if the type parameter has been defined for the class holding the dictionary. In other words, at compile time, the type of T is known.

So this will compile:

public class MyDictionaryWrapper<T>
{
   private Dictionary<int, A<T>> myDict;
}
womp
+1  A: 

Can you define a non-generic abstract or interface that all A<T> will implement? This was our solution to a similar problem in our project; we had web control ancestors that were generic to any of our domain classes, so the domain class could be passed in as the DTO and bound/unbound by the control's codebehind. The descendants closed the generic specification, but that ancestor had to stay open, so to allow for collections of these controls independent of domain type, we extracted a non-generic base class from the generic base. Defining an interface would work similarly.

KeithS
+1 I've found this to be a clean solution, as you really have to ask yourself, what are you planning to do with all those different generic types? If you don't have some standard interface, you're just doing check-type-and-do-specific-stuff logic, in which case you might as well store the types as Object.
Dan Bryant
Ok, turns out i DO need this construction :) O can't implement a non-generic interface for this type because the most important method on the objects is one that gets a parameter of the type T.
Jeroen
A: 

I worked around it by just storing a Type as the value and then work with that Type. Seemed like a cleaner solution.

Jeroen
A: 

I think I have to give up type safety in this case and remove the generic. I can't define a non-generic interface because the main method of this class receives an argument of the generic type and I can't make the containing class a generic one either.

However, since this method is currently the only one that has anything to do with the generic class I'm going to remove the generic and make the argument in the method of type object to workaround the problem. I'm going to have to check the type at the callers of this method.

Jeroen