Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are C# arrays covariant and what benefits does it bring?

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?

like image 606
Matt B Avatar asked Aug 18 '10 20:08

Matt B


People also ask

Why is C not A or B?

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.

Why C is a language?

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.

Why are we still using C?

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.

Why C is mostly used?

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.


2 Answers

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.

like image 57
mqp Avatar answered Sep 19 '22 15:09

mqp


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

like image 37
CaffGeek Avatar answered Sep 17 '22 15:09

CaffGeek