Possible Duplicate:
Generic type from string value
Given a scenario,
Class Car: Transport,
Class Bus: Transport,
Interface Transport,
Get(): Generics Method
Is it possible to do something like this?
Transport t= Get<"Car">(string color);
public T Get<T>(string color)
{
return new T(color);
}
P/S: There’s a reason to assign it as string, dynamically, regardless of return type.
If you want having
Getworks with a string you have two options:Add a non generic
Gettaking a Type as a paremter, something like:public object Get(Type t);so you can pass a type created form a string.
A second option could be reflection:
then you can invoke generic as if it was closed on to the type myType.
If I can suggest which one to use, and if you can refactor the
Getmethod, I would suggest adding a non generic version of that method. The reflection version works if you really can’t modify the library code. The drawback in using reflection is performance as you probably guess: you can decide if you can stay with it or not.EDIT
Of course, my discussion does not apply if your method is really just creating the final object:
In this case activator works as a charm by passing the complete type name:
You generally can create the type based on just the simple name ( Car,Bus, etc ) because you need to fully qualify with a namespace and an assebly if the type is not the ExecutingAssembly. In this case you have to use some convention/configuration to simplify the code readability.
ADDITION
If you need to pass parameters too, I think you can try to start using a simple IoC ( I would not recomend one in particular, choose one widely used you like ) that can solve all these issues for you.