Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0042 Using foreach with Arrays

In C# we can use foreach loop with array. using System; class Program { static void Main(string[] args) { int[] intArray = new int[10]; for (int i = 0; i < intArray.Length; i++) { intArray[i] = i; } foreach (int i in intArray) { Console.WriteLine(i); } } } The output: 0 1 2 3 4 5 6 7 8 9 With multidimensional arrays, you can use the same method to iterate through the elements: class MainClass { static void Main() { int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.Write("{0} ", i); } } } The output: 9 99 3 33 5 55