Why won\'t the following code work?
class parent {}
class kid:parent {}
List parents=new List;
It seems obvious t
Besides the lack of generic variance support in C# prior to version 4.0, List is mutable and so cannot safely be covariant. Consider this:
void AddOne(List arg) where T : new()
{
arg.Add(new T());
}
void Whoops()
{
List contradiction = new List();
AddOne(contradiction); // what should this do?
}
This would attempt to add a Parent to a List referenced via a List reference, which is not safe. Arrays are permitted to be covariant by the runtime, but are type-checked at mutation time and an exception is thrown if the new element is not assignable to the array's runtime element type.