Loading
Loading

Reputation: 1120

Cannot convert List<ClassA> to List<T>

I have a generic function like this:

public List<T> DoStuff<T>(){
    if(typeof(T) == typeOf(ClassA))
        return CreateListWithTypeA();
    if(typeof(T) == typeOf(ClassB))
        return CreateListWithTypeB();
}

And the helper here:

public List<ClassA> CreateListWithTypeA(){
    return new List<ClassA>();
}
public List<ClassA> CreateListWithTypeB(){
    return new List<ClassA>();
}

Error in DoStuff():

Cannot convert type System.Collection.Generic.List<ClassA> to System.Collection.Generic.List<T>

PS: ClassA & ClassB implement an interface. Not sure if this is helpful somehow

Upvotes: 1

Views: 78

Answers (2)

Sweeper
Sweeper

Reputation: 273968

I don't think this is a very good use of generics, as it limits T to be only one of two types.

But if you insist, here's how to fix your method:

public static List<T> GetList<T>() where T : YourInterface { // The constraint here provides just a *bit* more compile time checking
    if (typeof(T) == typeof(A)) {
        return CreateListWithTypeA().Cast<T>().ToList();
    }

    // other cases here...

    throw new Exception("T is not the right type!");
}

Upvotes: 4

TheGeneral
TheGeneral

Reputation: 81573

You could always just do this, however this is very very redundant

public List<T> DoStuff<T>()
{
   return new List<T>();
}

Assuming there is more going on in these helpers

public List<T> CreateListWithTypeA<T>(){
    return new List<T>();
}

...

if you need to access interface specific stuff use a constraints

where T : IMyLovelyHorse

If you need to new T up itself add new() constraints

where T : new()

Lastly, using if(typeof(T) == typeOf(ClassA)) patterns in a generic method usually point to something wrong and a need to think about things different, not always... though usually

Upvotes: 3

Related Questions