Home >Backend Development >C++ >Why Can't I Convert a `List` to a `List` in C#?

Why Can't I Convert a `List` to a `List` in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-30 13:06:11749browse

Why Can't I Convert a `List` to a `List` in C#?

Invariant List: Understanding the Conversion Restriction

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 is an example of an invariant collection. This means that a List cannot be assigned to a List because the compiler guarantees that all elements in a list will always be of the declared type T.

Implications of Invariance for List

The invariance of List protects against invalid operations that could violate type safety. For instance, if a List is assigned to a List, derived class instances could potentially be replaced with base class instances, leading to unexpected behaviors.

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, which is covariant. This allows the substitution of derived types for base types, resolving the conversion issue without compromising type safety.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn