title: How does `foreach` iterate through a 2D array?
body: <p>I was curious as to how a <code>foreach</code> loop in C# iterates over a multidimensional array. In the following code, the second nested <code>for</code> loop was originally a <code>foreach</code> which would give the incorrect position of the pitches placed in the loop. I know it's kind of difficult to intuit what it does, but it's basically this: Pitches are put into a multidimensional array (here, numVoices is 2 and exLength is 10) so that you will have a 2x10 array of pitches; each of these rows of pitches are then played at the same time by the MIDI output device. When I used a <code>foreach</code> to then put the pitches' names into a string so that I could display what pitches were in what place inside of the grid, the <code>foreach</code> would display them in the "wrong" order (i.e., [0,3] in the pitch grid was not what was printed in the string). Using a nested <code>for</code>, this problem disappeared. I tried to recreate this with a smaller example of a 2D list of <code>int</code>s (code below) but it gives the "right" answer this time. Why?</p>
  
  <pre><code>            //put pitches into grid
              //numVoices = 2, exLength = 10 (10 notes long, 2 voices)
              for (int i = 0; i &lt; numVoices; i++ )
              {
                  for(int j = 0; j &lt; exLength; j++)
                  {
                      //here we generate random pitches in different octaves
                      //depending on the voice (voice 2 is in octave
                      //below voice 1, etc)
                      randnum = (random.Next(100 - (i * 13), 112 - (i * 13)));                        
  
                      melodyGrid[j, i] = (Pitch)randnum;
  
                  }
              }
  
              for (int i = 0; i &lt; numVoices; i++)
              {
                  for (int j = 0; j &lt; exLength; j++)
                  {
                                       //this down here makes it more readable for
                                       //humans
                                       //e.g. "FSharp5" becomes "F#5"
  
                      noteNames += String.Format("{0, -6}", melodyGrid[j,i].ToString().Replace("Sharp", "#").Replace("Flat", "b"));
  
                  }
                  noteNames += "\r\n"; //lower voices are just separated by newlines
              }
              Console.WriteLine(noteNames);
  </code></pre>
  
  <p>The following code works "correctly," however:</p>
  
  <pre><code>int[,] nums = { {1, 2, 3}, 
                              {4, 5, 6},
                              {7, 8 ,9} };
              foreach (int i in nums)
              {
                  Console.Write("{0} ", i);
              }
  </code></pre>
  
  <p>Is it possible I was just making a semantic mistake? Or do <code>foreach</code> loops iterate through arrays in differing manners?</p>