Multidimensional Arrays in C#

Yesterday I was working with arrays and got hung up on a basic error message, a couple of them.

Object of type 'System.Int32[,]' cannot be converted to type 'System.Int32[][]
Cannot convert from an int[,] to an int[][]

There was not much on the internet that direct hit on these error strings (maybe it is too easy). Because of my java background it tripped me up for a few minutes.

Declaring a multidimensional array is not the same in C# as it is in Java.

//valid java, not valid in c#
int[][] array = new int[6][6];

In c# there are multidimensional arrays (think “matrix”) and jagged arrays (think “array of arrays”).

Multidimensional Array. Key points: simpler syntax but slower (more overhead). 2nd dimension the same length for all.

new int[6,6] {{-1, -1, 0, -9, -2, -2 },
{ -2, -1, -6, -8, -2, -5 },
{ -1, -1, -1, -2, -3, -4 },
{ -1, -9, -2, -4, -4, -5 },
{ -7, -3, -3, -2, -9, -9 },
{ -1, -3, -1, -2, -4, -5 } }

Jagged Array. 2nd dimension length can vary.

new int[6][] {new int[6] {-1, -1, 0, -9, -2, -2 },
new int[6] { -2, -1, -6, -8, -2, -5 },
new int[6] { -1, -1, -1, -2, -3, -4 },
new int[6] { -1, -9, -2, -4, -4, -5 },
new int[6] { -7, -3, -3, -2, -9, -9 },
new int[6] { -1, -3, -1, -2, -4, -5 } }

Once you realize this not-so-subtle difference there are lots of resources on the web available.

Resources

https://stackoverflow.com/questions/4648914/why-we-have-both-jagged-array-and-multidimensional-array

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays