Home >Backend Development >C++ >Why Can't I Directly Cast a `List` to a `List` in C#?
Casting 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
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
Safe Conversion Options
While you cannot directly cast a List
List<IFruit> fruit = apples.ToList<IFruit>();
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!