Using foreach with Arrays
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

Using foreach with Arrays (C# Programming Guide)

C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.Write("{0} ", i);
}
//Output: 4 5 6 1 2 3 -2 -1 0

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form: 
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } }; 

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

However, with multidimensional arrays, using a nested for loop gives you more control over the array elements.

Show:
© 2016 Microsoft