Home >Backend Development >C++ >Why Can't I Convert a `List` to a `List` in C#?
When passing a list of derived classes to a function that expects a list of base classes, developers may encounter the error:
cannot convert from 'System.Collections.Generic.List<ConsoleApplication1.DerivedClass>' to 'System.Collections.Generic.List<ConsoleApplication1.BaseClass>'
This error is not immediately intuitive, as one might assume that a list of derived classes should be compatible with a list of base classes. To understand the reason behind this restriction, it is essential to grasp the concept of covariance in generic collections.
Covariance and Invariance
Generic collections in C# can be either covariant or invariant. Covariant collections allow the substitution of derived types for their base types, while invariant collections do not.
List
Implications of Invariance for List
The invariance of List
Safe Alternative: IEnumerable
To safely pass a list of derived classes to a function that expects a list of base classes, developers can utilize IEnumerable
In the provided code snippet, the following modification addresses the error:
IEnumerable<BaseClass> bcl = new List<DerivedClass>(); public void doSomething(IEnumerable<BaseClass> bc) { // do something with bc }
The above is the detailed content of Why Can't I Convert a `List` to a `List` in C#?. For more information, please follow other related articles on the PHP Chinese website!