No it is not possible to cast a list to a list of it's subclasses. There is no reasonable way this could work without breaking type safety. Consider the following code if it were possible
List<Vertex> list1 = new List<Vertex>();
list1.Add(new Vertex());
List<Vertex2D> list2 = (List<Vertex2D>)list1;
Vertex2D vertex2d = list2[0]; // Oh no the first element is a Vertex!
The list list would have to throw an InvalidCastException
since you can't convert a Vertex
to a Vertex2D
.
However I suspect that your real issue is you want the list of vertex's in Vertex2D
that was inherited from Vertex
to change type. This is you have:
class Graph {
public List<Vertex> Vertices { get; set; }
}
class Graph2D : Graph {
// Now I want vertices to only contain Vertex2D!
}
You can accomplish this my making Graph generic on Vertex:
class GraphBase<TVertex> where TVertex : Vertex {
public List<TVertex> Vertices { get; set; }
}
class Graph : GraphBase<Vertex> {
}
class Graph2D : GraphBase<Vertex2D> {
}
This does break the inheritance relationship between Graph and Graph2D. If that's important I'd suggest implementing a non-generic interface. This interface can rely on the fact that IEnumerable is covariant on T:
interface IGraph {
IEnumerable<Vertex> Vertices { get;}
}
class GraphBase<TVertex> : IGraph where TVertex : Vertex {
public List<TVertex> Vertices { get; set; }
IEnumerable<Vertex> IGraph.Vertices { get { return Vertices; }}
}