Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning List<T> with different contents depending on T

Tags:

c#

generics

I want to do something like this:

public List<T> GetList<T>()
{
    if (typeof(T) == typeof(Type1))
    {
        return new List<Type1>() { new Type1(), new Type1(), new Type1() };
    }

    if (typeof(T) == typeof(Type2))
    {
        return new List<Type2>() {new Type2(), new Type2()};
    }

    throw new Exception("Unknown T");
}

public void DoStuffWithGenericList<T>()
{
    var list = GetList<T>();
    // do stuff that does not depend on T
}

But that, of course, is not legal. I feel I am missing something basic here :)

In my case, I am getting lists of different types of objects from Entity Framework, but the rest of my logic does not depend on the actual type. It can just work on List or it could be generic.

All Ts that GetList() will be called with as type parameter will inherit from the same base class, if it makes a difference.

like image 627
pinkfloydhomer Avatar asked Dec 16 '22 10:12

pinkfloydhomer


1 Answers

Why not use the 'new' operator to instantiate the types:

public List<T> GetList<T>() where T : new()
{
    if (typeof(T) == typeof(Type1)) 
    { 
        return new List<T>() { new T() }; 
    }                     
    // etc...
    throw new Exception("Unknown T");
}

All you have to do is ensure your types can be instantiated by adding the new() constraint.

like image 109
L-Four Avatar answered Jan 08 '23 16:01

L-Four