Covariance and Contravariance with C# Arrays
It's not safe at compile time. In other words, there's code which is legal by the language rules, but fails at execution time, without any explicit casting to give a big warning sign of "this might fail". The CLR makes sure that only valid writes succeed at execution time. For example:
string[] strings = new string[1];
object[] objects = strings;
objects[0] = new object();
That will throw an exception (ArrayTypeMismatchException
) at execution time. The alternative would have been to allow it at execution time, at which point strings[0]
would have been a reference to a non-string object, which would clearly be bad.
See also recent blog posts:
- One by me about performance and safety using a generic wrapper
- One on immutable arrays from the BCL team
- Part 2 of Eric Lippert's blog series on variance in general (the series is mostly aimed at generics, but this part is on arrays)