Cannot implicitly convert list of derived objects to generic IEnumerable where T is a base type

  Kiến thức lập trình

I have a type system like

class Base {}
class Derived1 : Base {}
class Derived2 : Base {}

I have also collections of derived types

class MyClass
{
    List<Derived1> Derived1Collection { get; set; }
    List<Derived2> Derived2Collection { get; set; }
}

I want to have a generic method that returns any from these collections like GetData<Derived1>(). Have implemented it like so:

class MyClass
{
    public static IEnumerable<T> GetData<T>() where T : Base
        => typeof(T) switch // dummy "typeof(T)"
        {
            _ when typeof(T) == typeof(Derived1) => Derived1Collection,
            _ when typeof(T) == typeof(Derived2) => Derived2Collection,
            _ => throw new NotSupportedException($"{typeof(T)} isn't supported."),
        };
}

For every returning of derived collection it writes an error like “Cannot implicitly convert type List<Derived1> to IEnumerable<T>“. But after adding casting at each derived collection it is gone, so this works:

_ when typeof(T) == typeof(Derived1) => Derived1Collection.Cast<T>(),
_ when typeof(T) == typeof(Derived2) => Derived2Collection.Cast<T>(),

Why so?

1

LEAVE A COMMENT