How to create a generic list in this wierd case in c#

Posted by Marc Bettex on Stack Overflow See other posts from Stack Overflow or by Marc Bettex
Published on 2010-06-03T11:02:22Z Indexed on 2010/06/03 11:04 UTC
Read the original article Hit count: 252

Filed under:
|
|
|

Hello,

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 a instance of B or C (or of one of the other child), 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 to 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 will guess the type of model, but it doesn't work and return a List<A>. I believe that because c# is statically typed, T is resolved as A and not as the real type of model at runtime.

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,
Marc

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics