I understand that the List<> of derived class cannot be directly assigned to List<> of base class. But how does it allow assigning the same List<> of derived class to an IEnumerable<> type of base class parameter.
public class Base
{}
public class Derived : Base
{}
public class Test
{
// inside some method...
List<Derived> someElements;
ReadElements(someElements);
public void ReadElements(List<Base> elements) // this throws compile error
{...}
public void ReadElements(IEnumerable<Base> elements) // this one works
{...}
}
I know that the List is an implementation of IEnumerable and support indexing and modifying elements, but I don’t seem to understand this part? Can someone please explain?
Thanks.
Because the declaration of
IEnumerable<T>is in fact:…and the
outbit means thatTis covariant and accepts subtypes.Whereas the declaration of
List<T>has no variance annotation and therefore theTis invariant.