How do i go from (cast?, convert?):
IEnumerable<Square>
to
IEnumerable<Shape>
How do i go from (cast?, convert?):
IEnumerable<Square>
to
IEnumerable<Shape>
If you're using anything lower than .NET 4.0, then you're going to have to use IEnumerable.Cast:
IEnumerable<Square> squares = new List<Square>();
// Fill the collection
IEnumerable<Shape> shapes = squares.Cast<Shape>();
.NET 4.0 introduces new Covariance and Contravariance features that allow you to make that cast directly:
IEnumerable<Square> squares = new List<Square>();
IEnumerable<Shape> shapes = (IEnumerable<Shape>)squares;
If you're using .NET 4.0, you don't have to.
From Covariance and Contravariance in Generics (emphasis added):
Polymorphism enables you to assign an instance of Derived to a variable of type Base. Similarly, because the type parameter of the IEnumerable(T) interface is covariant, you can assign an instance of
IEnumerable<Derived>
to a variable of typeIEnumerable<Base>
...
Since you're asking this question, I assume you're not using .NET 4.0 yet. But this might be a reason to upgrade, if you're able to.