C # array type declaration in reverse order

I have only one of these "What ..." moments. Is the following purpose and is there any obscure reasoning behind the "unnatural" declaration of arrays in C #?

int[,][] i; // declares an 2D - array where each element is an int[] ! // you have to use it like this: i = new int[2,3][]; i[1,2] = new int[0]; 

I would expect another. int [,] [] declares a 1-dimensional array, where each element is a two-dimensional array.

Funny, however, the type name is reversed:

 Console.WriteLine(typeof(int[,][]).Name); // prints "Int32[][,]" 

Can someone explain this? Is it intentional? (Using .NET 4.5 under Windows.)

+7
source share
2 answers

You can find a lengthy discussion on Eric Lippert's blog Arrays of Arrays .

What C # actually does

This is a mess. No matter which option we choose, something ultimately does not match our intuition. This is what we actually chose in C #.

First: the second option [This is a two-dimensional array, each element is a one-dimensional array of integers] is correct. We make you live with the oddities caused by the First Investigation; you don’t actually turn the element type into an array of this type by adding an array specifier. You turn it into an array type by adding a qualifier to the list of existing array specifiers. Crazy but true.

The word "prefix" partially explains your derivation of the return type name. A CLR type name does not necessarily match a C # declaration.

But a more relevant quote below:

However, multidimensional torn arrays are almost certainly an unpleasant smell of code.

+8
source

I had the same "what ..." the first time I saw new int[5][]; instead of new int[][5]; .

An EL (very nice) blog post dances around one thing: there is an ideal way to do this for people with a ComSci degree, but there is no good way to do it for others. If you just follow the grammar, you point from right to left, new from right to left and pointer from left to right:

 // 1D array of 2D arrays, no special rules needed: int[,][] N; N=new[,][5]; N[0]=new int[4,4]; 

But the target audience of C # is not people with 4-year degrees of CS (who have all seen the reverse Polish language and love right to left.) The trick, IMHO, in the understanding of C # arrays with teeth, is that they decided to make special rules for them when they did not need technical support.

0
source

Source: https://habr.com/ru/post/925933/


All Articles