In C#, is it possible to cast a List<Child> to List<Parent>?
I want to do something like this:
List<Child> childList = new List<Child>();
...
List<Parent> parentList = childList;
However, because parentList is a List of Child's ancestor, rather than a direct ancestor, I am unable to do this. Is there a workaround (other than adding each element individually)?
Using LINQ:
List<Parent> parentList = childList.Cast<Parent>().ToList();
Documentation for Cast<>()
Casting directly is not allowed because there's no way to make it typesafe. If you have a list of giraffes, and you cast it to a list of animals, you could then put a tiger into a list of giraffes! The compiler wouldn't stop you, because of course a tiger may go into a list of animals. The only place the compiler can stop you is at the unsafe conversion.
In C# 4 we'll be supporting covariance and contravariance of SAFE interfaces and delegate types that are parameterized with reference types. See here for details:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/