In my program, I have a class A which is extended by B, C and many more classes. I have a method GetInstance() which returns an instance of B or C (or of one of the other children), but I don’t know which one, so the return type of the method is A.
In the method CreateGenericList(), I have a variable v of type A, which is in fact either a B, a C or another child type and I want to create a generic list of the proper type, i.e. List<B> if v is a B or List<C> if v is a C, …
Currently I do it by using reflection, which works, but this is extremely slow. I wanted to know if there is another way to do it, which doesn’t use reflection.
Here is an example of the code of my problem:
class A { }
class B : A { }
class C : A { }
// More childs of A.
class Program
{
static A GetInstance()
{
// returns an instance of B or C
}
static void CreateGenericList()
{
A v = Program.GetInstance();
IList genericList = // Here I want an instance of List<B> or List<C> or ... depending of the real type of v, not a List<A>.
}
}
I tried the following hack. I call the following method, hoping the type inferencer would guess the type of model, but it doesn’t work and returns a List<A>. I believe that because c# is statically typed, T is resolved as an A and not as the real type of model at run-time.
static List<T> CreateGenericListFromModel<T>(T model) where T : A
{
return new List<T> ();
}
Does anybody have a solution to that problem that doesn’t use reflection or that it is impossible to solve that problem without reflection?
Thank you very much.
You can’t solve this Problem without reflection, as generic type parameters have to be known at compile time. If you know what type you have (eg. by
if(v[0] is B)) you can usev.Cast<B>()to convert it from aList<A>toIEnumerable<B>, which you can turn into a list again by callingToList().