I'm having trouble understanding why arrays in C# are covariant and what benefits this covariance can bring. Consider the following trivial code example:
object[] myArray = new string[1];
myArray[0] = 1;
This code will compile okay, but will unceremoniously and perhaps unsurprisingly explode at runtime.
If I try to attempt this same thing using generics, the compiler would grumble at me and I would realise my stupidity at an early stage, so my question is this: Why does the C# compiler allow this covariance with arrays and furthermore, what are the potential benefits?
Because C comes after B The reason why the language was named “C” by its creator was that it came after B language. Back then, Bell Labs already had a programming language called “B” at their disposal.
As a middle-level language, C combines the features of both high-level and low-level languages. It can be used for low-level programming, such as scripting for drivers and kernels and it also supports functions of high-level programming languages, such as scripting for software applications etc.
The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.
The C programming language is the recommended language for creating embedded system drivers and applications. The availability of machine-level hardware APIs, as well as the presence of C compilers, dynamic memory allocation, and deterministic resource consumption, make this language the most popular.
Eric Lippert says:
Unfortunately, this particular kind of covariance is broken. It was added to the CLR because Java requires it and the CLR designers wanted to be able to support Java-like languages. We then up and added it to C# because it was in the CLR. This decision was quite controversial at the time and I am not very happy about it, but there’s nothing we can do about it now.
Eric Lippert has a writeup about this (Actually a long series about 'variance', 11 parts I think)
http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx
And some more interesting stuff
http://blogs.msdn.com/b/ericlippert/archive/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With