Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how can I do a Dictionary of generics? [duplicate]

Tags:

c#

generics

Lets say I have Generic class Foo<T>.

What i want to do is create a singleton for each of a variety of T, and then quickly retrieve them by T later on.

in pseudocode

STORE new Foo<int>
STORE new Foo<MyClass>

GET instance for MyClass  ->  returns the Foo<MyClass> created above.

In Java I'd make a dictionary that had Type for the key and Foo<*> for the value.

What is the equivalent magic in C#?

like image 657
user430788 Avatar asked Dec 26 '22 22:12

user430788


2 Answers

Dictionary<Type, object> Dict = new Dictionary<Type, object>();

void Store<T>(Foo<T> foo)
{
    Dict.Add(typeof(T), foo);
}

Foo<T> Retrieve<T>()
{
    return Dict[typeof(T)] as Foo<T>;
}
like image 128
Seva Alekseyev Avatar answered Jan 22 '23 00:01

Seva Alekseyev


There are two ways a method may be given a type: as a Type parameter, or as a generic type parameter. In the former case, if the generic class Foo<T> inherits from a base class (e.g. FooBase) which is not generic in type T, one may use a Dictionary<Type,FooBase>. The FooBase class can include all the members (perhaps as abstract or virtual) of Foo<T> whose signature doesn't depend upon T, so code which is given a Type object for an arbitrary type but does not have a generic type parameter will be able to do with a FooBase anything that could be done without having a generic type parameter. Note that if one has a Type object and wants to use it as though it were a generic type, one will generally have to use Reflection and construct either a delegate or a generic class class instance with the type parameter filled in; once one has done that, one may use the second approach below.

If one has a generic type parameter available (e.g. one is writing a method T GetThing<T>(whatever), one may define a static generic class ThingHolder<T> with a static field T theThing. In that case, for any type TT, ThingHolder<TT>.theThing will be a field of type TT. One will be able to do with this field anything that can be done with a TT.

like image 45
supercat Avatar answered Jan 22 '23 01:01

supercat