In C#, when you "new" an array, it looks like this:
int[] someArray = new int[5];
Which I read as:
int-array someArray = new int-array-of-size-5
Today I casually tried to create an array of arrays like so:
int[][] someArray = new int[][5];
To me, that made intuitive sense - I would read it like:
int-array-array someArray = new int-array-array-with-size-5
However, after getting a confusing error and googling it, I found that it should be written this way instead:
int[][] someArray = new int[5][];
That doesn't make sense to me - because I read it like so:
int-array-array someArray = new int-array-with-size-5-array
But I'm not creating an array of size-5-int-arrays, I'm creating an array of int-arrays with size 5.
What is the underlying design rationale for the syntax? How am I intended to interpret int[5][] - what mental model can I use to make sense of this syntax?
Array of arrays
As this blog post explains, they wanted to keep the order of brackets the same when creating an array and when accessing elements of the array. I'll try to summarize.
When you access an array like this:
that means: take the array at index 1 and get the element of that array at index 2. So, when creating the array, you have to initialize it like so:
which means an object that holds 5 int arrays. Weirdness cannot be avoided. Either the order of the brackets is weird when creating the array or the order is weird when accessing the array. The weirdest option would be when the order is different both times.