How Can I Safely Cast a List to List in C#?
Jan 09, 2025 pm 10:36 PMConvert List<Derived Class> to List<Base Class>
in C#When dealing with inheritance, it is sometimes necessary to convert a list of derived class objects into a list of base class objects. However, this can lead to errors if not handled properly.
Error in list conversion using writable data
Consider the following code:
using System; using System.Collections.Generic; class Animal { public virtual void Play(List<Animal> animal) { } } class Cat : Animal { public override void Play(List<Animal> animal) { } } class Program { static void Main(string[] args) { Cat cat = new Cat(); cat.Play(new List<Cat>()); } }
This code will generate a compilation error due to a mismatch in the list object types. Animal expects a list of its own type (Animal), but this method is called with a list of Cat objects.
Error reason
This error occurs because the list is writable. If the conversion is allowed, it may cause data manipulation problems. For example, a dog object could be added to a list of cats, which would violate type safety.
Generic covariance
In C# 4, a feature called generic covariance was introduced. This allows a list of derived classes to be converted to a list of base classes, provided these types ensure type safety. An example of a safe type for generic covariance is IEnumerable<T>
, which represents a sequence of objects but cannot be written to.
Implementing generic covariance
To implement generic covariance, you can change the method signature in the base class to use IEnumerable<T>
as the parameter type, like this:
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>()); } }
In this example, the Play method in Animal takes IEnumerable<Animal>
as a parameter, which allows it to accept a sequence of Animal and Cat objects.
The above is the detailed content of How Can I Safely Cast a List to List in C#?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

C language function format letter case conversion steps

What are the definitions and calling rules of c language functions and what are the

Where is the return value of the c language function stored in memory?

How does the C Standard Template Library (STL) work?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?
