Published Aug 29, 2019
Quick question for you: what’s the difference between this syntax
static void UseMultidimensionalArray(int[][] multidimensionalArray)
{
Console.WriteLine(multidimensionalArray[0][0]);
}
and this syntax?
static void UseMultidimensionalArray(int[,] multidimensionalArray)
{
Console.WriteLine(multidimensionalArray[0,0]);
}
I was recently working on a problem that involved a two-dimensional array and found myself stumbling over this small syntax difference.
Now, I probably haven’t had to deal with multidimensional arrays since computer science classes in college. It turns out that’s why I was getting tripped up. Back then, I was working in C++ and Java and if you wanted a 2x2
matrix, you declared or initialized it with those dimensions:
// C++
int twoByTwo[2][2] = { {1,2}, {3,4} };
// Java
int[][] twoByTwo = new int[2][2];
But in C#, if you ever find yourself writing [2][2]
to declare or initialize an array, you’re doing something wrong. This is a compilation error:
var twoByTwo = new int[2][2];
But these aren’t:
var twoByTwo_v1 = new int[2][];
var twoByTwo_v2 = new int[2,2];
The first version is a jagged array, meaning that each array entry is an array of potentially different length e.g.
int[][] jaggedArray = new int[2][] {
new int[1] {44},
new int[3] {1,2,3}
};
Console.WriteLine(jaggedArray[1][1]); // 2
The second version is what we want if we’re looking for rigid dimensions e.g.
int[,] twoByTwo = new int[2,2] {
{1,2},
{3,4}
};
Console.WriteLine(twoByTwo[0,1]); // 2
It boils down to the following in C#: