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#?
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>;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With