Think fast! What will this code print?

int[,] nums = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

foreach (var num in nums)
{
    Console.WriteLine(num);
}

If you’re like me, you probably thought you’d see this output:

System.Int32[]
System.Int32[]
System.Int32[]

That is, you figure that the “foreach” will iterate over the array of arrays, and try to print out each array.

I can tell you now that that’s not the case. If you compile the code and run it, you’ll find it prints this:

1
2
3
4
5
6

WTF? Iterating over an array of arrays actually flattened the array for me? Why yes, yes it did! Have a look at this article from the MSDN C# Programming Guide called Using foreach with Arrays. When you iterate over a multidimensional array, you get each element of the array rather than each “row”.

I figured I’d try something else after discovering this, and wrote this piece of code:

int[,] nums = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

for (int i = 0; i < nums.Length; i++)
{
    for (int j = 0; j < nums[i].Length; j++)
    {
        Console.WriteLine(nums[i, j]);
    }
}

Surely that’s reasonable? A nested “for” loop over my multidimensional array? Guess what? It doesn’t even compile! You get this error on the “nums[i]” line:

Wrong number of indices inside []; expected '2'

So it turns out that multidimensional arrays in C# are not the same as arrays of arrays (also called jagged arrays because each element of the array might be an array of any size). The compiler treats these two objects very differently:

int[,] array1;
int[][] arrays2;

I’d love to hear from a C# guru on this one. I guess I just don’t use arrays enough to have known this, preferring instead to use generic collections and the like.