Is there a way to create a generic class from type parameter.
I have something like this:
public class SomeClass
{
public Type TypeOfAnotherClass { get; set; }
}
public class OneMoreClass
{
}
public class GenericClass<T>
where T : class
{
public void DoNothing() {}
}
public class GenericClass
{
public static GenericClass<T> GetInstance<T>(T ignored)
where T : class
{
return new GenericClass<T>();
}
}
What I want is to create a GenericClass from a Type. Ex:
var SC = new SomeClass();
SC.TypeOfAnotherClass = typeof(OneMoreClass);
var generic = GenericClass.GetInstance(SC.TypeOfAnotherClass);
Assert.AreEqual(typeof(GenericClass<OneMoreClass>), generic.GetType());
Here I expect to get instance of GenericClass<OneMoreClass> but I get GenericClass<Type>
I also tried using instance of that type. Ex:
var generic = GenericClass.GetInstance(Activator.CreateInstance(SC.TypeOfAnotherClass));
This time I get GenericClass<object>
Is there a way to accomplish this task?
If you know the type you actually want (
OneMoreClass) at build time, then you should just use it:But I am assuming you don’t know it at build time, and have to get the
typeat runtime.You can do it with reflection, but it isn’t pretty, and is slow:
Since you don’t know the resulting type at build time, you can’t return anything but
object(ordynamic) from the method.Here is how much slower (for 100,000 creates)
Results:
So a little over 100x slower.
The real thing to note about generics is that the
<T>s in generics are resolved at build-time by the C# compiler, and the real class names are inserted. When you have to defer that until run-time, you end up paying the performance price.