Cannot convert from List<DerivedClass> to List<BaseClass>
Solution 1:
It is because List<T>
is in-variant
, not co-variant
, so you should change to IEnumerable<T>
which supports co-variant
, it should work:
IEnumerable<BaseClass> bcl = new List<DerivedClass>();
public void doSomething(IEnumerable<BaseClass> bc)
{
// do something with bc
}
Information about co-variant in generic
Solution 2:
Explanations that I have found have simply said that it violates type safety somehow, but I'm not seeing it. What is the risk of the compiler allowing conversion from
List<DerivedClass>
toList<BaseClass>
?
This question is asked almost every day.
A List<Mammal>
cannot be converted to a List<Animal>
because you can put a lizard into a list of animals. A List<Mammal
> cannot be converted to a List<Giraffe>
because there might be a tiger in the list already.
Therefore List<T>
has to be invariant in T.
However, List<Mammal>
can be converted to IEnumerable<Animal>
(as of C# 4.0) because there is no method on IEnumerable<Animal>
that adds a lizard. IEnumerable<T>
is covariant in T.