How do I convert a List<interface> to List<concrete>?
A List<MyInterface>
cannot be converted to a List<MyClass>
in general, because the first list might contain objects that implement MyInterface
but which aren't actually objects of type MyClass
.
However, since in your case you know how you constructed the list and can be sure that it contains only MyClass
objects, you can do this using Linq:
return list.ConvertAll(o => (MyClass)o);
But a List<MyInterface>
is emphatically not a List<MyClass>
.
Think:
interface IAnimal { }
class Cat : IAnimal { }
class Dog : IAnimal { }
var list = new List<IAnimal> { new Cat(), new Dog() };
Then
var cats = (List<Cat>)list;
Absurd!
Also,
var cats = list.Cast<Cat>();
Absurd!
Further
var cats = list.ConvertAll(x => (Cat)x);
Absurd!
Instead, you could say
var cats = list.OfType<Cat>();
You could use Cast<>
extension method:
return list.Cast<MyClass>();