Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic types, collections and object reference

Tags:

c#

generics

I have a generic type GenericClass<Type_T> (Type_T implements IType_T if it helps). I create some instances of it, for example GenericClass<Type1>, GenericClass<Type2>.

No I want an index over a bunch of theses class instances. I first thought about a dictionary : Dictionary<int, GenericClass<Type1>> which obviously doesn't work.

Is there a known solution to this problem ? How to store an indexed collection of generic types ?

like image 790
Nicolas Voron Avatar asked Dec 14 '22 12:12

Nicolas Voron


1 Answers

Normally what you do in this case is create a common non-generic base class (sometimes an abstract class, or a non-generic interface), GenericClass, from which GenericClass<Type_T> derives, and that contains the methods that don't have as a parameter/return type the Type_T. You use this base class/interface exactly for what you wrote: Dictionary<int, GenericClass>...

A race-to-the-bottom is: Dictionary<int, object>, because object is the base class for all the class types in .NET.

Classical case: List<T> derives from IList, ICollection, IEnumerable.

like image 193
xanatos Avatar answered Dec 31 '22 10:12

xanatos