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

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

DDD
DDDOriginal
2025-01-17 01:01:12326browse

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

Casting List to List

Consider the following code:

public interface IDic
{
    int Id { get; set; }
    string Name { get; set; }
}
public class Client : IDic
{

}

List<Client> clients = new List<Client>();

Many programmers may assume that they can cast this List to a List:

List<IDic> dics = (List<IDic>)clients;

However, this is not a valid cast. This type of cast is not allowed because it would violate type safety. If you attempt this cast, the following error will occur:

Cannot convert type 'System.Collections.Generic.List<Client>' to 'System.Collections.Generic.List<IDic>'

Why is this Cast Not Allowed?

The reason this cast is disallowed is due to the potential for unsafe behavior. For example, imagine this scenario:

public interface IFruit {}

public class Apple : IFruit {}
public class Banana : IFruit {}

...

List<Apple> apples = new List<Apple>();
List<IFruit> fruit = (List<IFruit>)apples; // Assumed cast
fruit.Add(new Banana());

// Eek - it's a banana!
Apple apple = apples[0];

In this example, the List is cast to a List. This allows a Banana object to be added to the fruit list. However, when the first element of the apples list is accessed, it is still treated as an Apple. This can lead to unexpected behavior and potential bugs.

Safe Conversion Options

While you cannot directly cast a List to a List, there are safe ways to convert between these types.

  • ToList(): In .NET 4.0 and above, you can use the ToList() method to convert a List to a new List. This method creates a new list with the same elements but using the specified interface type.
List<IFruit> fruit = apples.ToList<IFruit>();
  • Cast().ToList(): In .NET 3.5, you can use the Cast() method to get an IEnumerable from a List. Then, you can use ToList() to create a new List from the IEnumerable.
List<IFruit> fruit = apples.Cast<IFruit>().ToList();

It's important to note that these conversions create new lists. Changes made to one list will not be reflected in the other. However, changes made to the objects in the lists will be visible in both lists.

The above is the detailed content of Why Can't I Directly Cast 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