Home > Backend Development > C++ > How Can I Cast a List to a List in C#?

How Can I Cast a List to a List in C#?

DDD
Release: 2025-01-09 22:41:41
Original
381 people have browsed it

How Can I Cast a List to a List in C#?

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template