Casting List – covariance/contravariance problem

The simplest way is probably to use ConvertAll:

List<IMyClass> converted = original.ConvertAll<IMyClass>(x => x);

Even if you’re using .NET 2, you can use lambda syntax if you’re using VS2008 or higher. Otherwise, there’s always anonymous methods:

List<IMyClass> converted = original.ConvertAll<IMyClass>(
    delegate (MyClass x) { return x; });

In .NET 3.5 you could use LINQ with Cast, OfType or even just Select:

var converted = original.Cast<IMyClass>().ToList();
var converted = original.OfType<IMyClass>().ToList();
var converted = original.Select(x => (IMyClass) x).ToList();

In .NET 4.0 you can use ToList directly without an intermediate cast, due to the covariance of IEnumerable<T>:

var converted = original.ToList<IMyClass>();

Leave a Comment