I have an object hierarchy
public class MyBase {}
public class MyDerived : MyBase {}
and have
List<MyBase> myList;
that is actually filled with instances of MyDerived
In order to access that list as a List<MyDerived>, I’m doing the following:
myList.Cast<MyDerived>().ToList()
I read the MSDN docs on Enumerable.Cast<T>, but it’s not clear to me whether the Cast<T> and ToList operations make a new copy of the objects in memory, or simply allow the compiler to access the existing objects as if they were a List<MyDerived>.
As its name implies,
Cast<T>()just casts objects:In .Net, it is fundamentally impossible to copy an arbitrary object. It would make no sense for
Cast<T>()to copy things.Note that if
Tis a value type,Cast<T>()will copy the structs; value types are always copied. (except when passed asrefparameters)