This is "sort of" possible. Sort of in that you can do it, but it's a bit of a hack.
You have 3 options:
If you know your classes up front, use a switch statement. Basically like this:
switch(str){
case "TypeRepository": return new Repository<TypeRepository>;
}
As a more advanced form of the above, you can use a dictionary instead of a hashtable
var factory = new Dictionary<string, Func<object>>();
factory.Add( "TypeRepository", () => new Repository<TypeRepository>() );
var theObject = factory["TypeRepository"]() as Repository<TypeRepository>;
For the greatest flexibility, You can use reflection to match strings to classes at runtime. Be aware that reflection is fairly slow, so if you're doing this with any kind of regularity, you want to avoid it. As an example, Here's one using Frans Bouma's method. Just change List<>
to Repository<>
in your code:
public static object MakeList( string typeStr )
{
var nameSpace = "MyTestApplication" + ".";
var objType = Type.GetType(nameSpace + typeStr); // NAMESPACE IS REQUIRED
var listType = typeof(List<>).MakeGenericType(objType);
return Activator.CreateInstance(listType);
}
var listOfThings = MakeList("MyCoolObject") as List<MyCoolObject>;
Note: There's no way to avoid the fact that all these mechanisms return object
, which you then have to cast to your proper type, rather than returning just returning strongly typed values.
This is unavoidable, because you don't know the type of the list until runtime, and C# is built around knowing things at compile time (this is what people mean when they say "statically typed programming language"). It will be less painful in C#4, where you'll be able to return dynamic
, which will save you the casting.