Cast List to List

You can’t cast it (preserving reference identity) – that would be unsafe. For example:

public interface IFruit {}

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

...

List<Apple> apples = new List<Apple>();
List<IFruit> fruit = apples; // Fortunately not allowed
fruit.Add(new Banana());

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

Now you can convert a List<Apple> to an IEnumerable<IFruit> in .NET 4 / C# 4 due to covariance, but if you want a List<IFruit> you’d have to create a new list. For example:

// In .NET 4, using the covariance of IEnumerable<T>
List<IFruit> fruit = apples.ToList<IFruit>();

// In .NET 3.5
List<IFruit> fruit = apples.Cast<IFruit>().ToList();

But this is not the same as casting the original list – because now there are two separate lists. This is safe, but you need to understand that changes made to one list won’t be seen in the other list. (Modifications to the objects that the lists refer to will be seen, of course.)

Leave a Comment