Covariance and Contravariance with C# Arrays [duplicate]

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:

Leave a Comment