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

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

Patricia Arquette
Release: 2025-01-09 22:32:47
Original
298 people have browsed it

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

Convert derived class list to base class list

Covariance means that a derived type can replace its base type without losing any functionality. In this case, we have a base class (Animal) and a derived class (Cat), where the base class contains a virtual method Play that accepts a List as input parameter.

The following code demonstrates the conversion problem:

<code class="language-csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication9
{
    class Animal
    {
        public virtual void Play(List<Animal> animals) { }
    }
    class Cat : Animal
    {
        public override void Play(List<Animal> animals)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat();
            cat.Play(new List<Cat>());
        }
    }
}</code>
Copy after login

Compiling the code will result in the error: Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'.

This error occurs because List is a writable data structure. If we allow conversion from List to List, dogs can be added to the list of cats, which may lead to unexpected behavior.

To solve this problem, C# 4 introduced a concept called "generic covariance" for known-safe interfaces. IEnumerable is such an interface. Since IEnumerable does not allow mutation, it is considered covariantly safe.

We can solve the conversion problem by modifying the Play method to accept an IEnumerable instead of a List:

<code class="language-csharp">class Animal
{
    public virtual void Play(IEnumerable<Animal> animals) { }
}
class Cat : Animal
{
    public override void Play(IEnumerable<Animal> animals) { }
}
class Program
{
    static void Main()
    {
        Cat cat = new Cat();
        cat.Play(new List<Cat>());
    }
}</code>
Copy after login

By using the IEnumerable<T> interface instead of List<T>, we take advantage of the covariance feature of C#, avoid type conversion errors, and ensure the safety of the code. IEnumerable<T> only allows data to be read, not modified, so it is safe to convert List<Cat> to IEnumerable<Animal>.

The above is the detailed content of 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template