foreach loops

Just a quick note here on foreach loops. Not sure if you knew this but foreach loops can be used to iterate over multidimensional arrays.

Imagine you have:

int[,,] myInts = {{ { 0, 1, 2 }, { 3, 4, 5 } }, { { 0, 1, 2 }, { 3, 4, 5 } }};

you can iterate over the whole 3D array here in a single foreach:

foreach (int i in myInts)

The resulting output is: 012345012345


If you want to use foreach to access arrays of ints in a multidimensional array you have to declare the array as if you were declaring a jagged array. The flaw with this is that you will be unable to use foreach to access all elements of the array directly but must instead access the arrays to access the elements. Basically int[][] != int[,] as the first one is an array of arrays and the second one is a multidimensional array. I suppose it makes since if you think of arrays in C# terms as objects instead of C/C++ as memory locations.

int[][] myInts = new int[][]{ new int[]{ 0, 1, 2 }, new int[]{ 3, 4, 5, 6 } };
foreach(int[] childArray in myInts)
    foreach(int child in childArray)
//no longer works
//foreach (int i in myInts)
//    Debug.Write(i.ToString());

Leave a Reply