Converting a List of Derived Classes to a List of Base Classes in C#
This example demonstrates a common problem: passing a list of derived class objects (e.g., List<Cat>
) to a method expecting a list of base class objects (List<Animal>
). Direct assignment isn't allowed because a base class reference cannot directly point to a derived class object.
The Issue:
Attempting to pass a List<Cat>
to a method with a List<Animal>
parameter results in a compiler error.
The Solution: Using IEnumerable
and Covariance
The solution leverages C#'s generic covariance. Instead of using List<Animal>
, change the method parameter type to IEnumerable<Animal>
. IEnumerable
is a read-only interface; this prevents the method from modifying the original collection, addressing potential type safety concerns.
Revised Code:
<code class="language-csharp">class Animal { public virtual void Play(IEnumerable<Animal> animals) { } } class Cat : Animal { public override void Play(IEnumerable<Animal> animals) { //Implementation } } class Program { static void Main() { Cat myCat = new Cat(); myCat.Play(new List<Cat>()); // This now compiles successfully } }</code>
This works because List<Cat>
implicitly converts to IEnumerable<Cat>
, and IEnumerable<Cat>
is covariant with IEnumerable<Animal>
. The Play
method can now safely iterate through the collection without attempting to modify it. This approach maintains type safety while allowing for flexible method parameterization.
The above is the detailed content of How Can I Cast a List to a List in C#?. For more information, please follow other related articles on the PHP Chinese website!