Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are jagged arrays in C# defined in the opposite way?

Let's say I have a type called T. Now let's say I make an array of type T, it gives me T[]. In code, it gives:

var myArray = new T[10];

With a length of 10. So, we can see that this makes an array that contains 10 items of type T. This works if T is int, string, BinaryWriter or anything standard. But let's say T is an array type, like int[] or string[].

Then, if we want to define an array of 10 items of type T (int[]), it should give something like this:

var myArray = new int[][10];

By replacing T by int[] in the previous example. But this gives a syntax error, because the correct syntax in C# is:

var myArray = new int[10][];

Which, if we followed the logic of the first example, should give an array containing an undefined amount of arrays containing 10 integers.

The same applies for any dimension of jagged arrays:

var myArray = new int[][][10];

Is wrong because the syntactically correct way is:

var myArray = new int[10][][];

This isn't a personal preference or a code style debate, but simply logic: why is the syntax different when we define arrays of array types, than when we define arrays of anything else?

like image 857
zdimension Avatar asked Mar 08 '23 17:03

zdimension


1 Answers

This way, the initialization syntax mirrors the access syntax.

var myArray = new int[NUM_ROWS][];
...
/* Initialize rows of myArray */
...
var x = myArray[0][5]; /* Should this be row 0, col 5; or row 5, col 0? */

It would be counterintuitive for myArray[0][5] to be parsed as (myArray[5])[0] since the indices would be inverted left-to-right, so we instead have myArray[0][5] parsed as (myArray[0])[5].

As such, in myArray[i][j], i corresponds to the index into the two-dimensional array, and j corresponds to the index into the one-dimensional array myArray[i].

Now, i can range from 0 to NUM_ROWS-1, so it is symmetrical with the access syntax to initialize var myArray = new int[NUM_ROWS][]. This way, the left set of brackets still corresponds to the length of the two-dimensional array, and the right set of brackets still corresponds to the one-dimensional array.

Edit: I see someone posted in the comments a link to an article where Eric Lippert goes through a more elaborate example and justification.

like image 135
Nick Avatar answered Mar 29 '23 06:03

Nick