This is the basic example of the foreach statement. The foreach statement iterates through a collection that implements the IEnumerable interface. In contract to for statement, the foreach statement does’t use the indexes.
1 2 3 4 5 6 7 | var names = new List<string>() { "John", "Tom", "Peter" }; foreach (string name in names) { Console.WriteLine(name); } |
Foreach with Continue
If the continue statement is used within the loop body, it immediately goes to the next iteration skipping the remaining code of the current iteration.
1 2 3 4 5 6 7 8 9 10 11 | var names = new List<string>() { "John", "Tom", "Peter" }; foreach (string name in names) { if (name == "Tom") { continue; } Console.WriteLine(name); } |
Output:
John Peter
Foreach with Break
If the break statement is used within the loop body, it stops the loop iterations and goes immediately after the loop body.
1 2 3 4 5 6 7 8 9 10 11 12 | var names = new List<string>() { "John", "Tom", "Peter" }; foreach (string name in names) { if (name == "Tom") { break; } Console.WriteLine(name); } Console.WriteLine("OK"); |
Output:
John
OK
Foreach Under the Hood (Foreach Implemented by While)
The following example shows how can be foreach statement implemented using while statement. It shows what .NET Framework have to do under the hood. First the IEnumerable collection is asked to create new enumerator instance (which implements IEnumerator). Then it calls IEnumerator.MoveNext() method until it returns false. For each iteration it obtains value from IEnumerator.Current property.
C# Foreach Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 | static void Main(string[] args) { var names = new List<string>() { "John", "Tom", "Peter" }; foreach (string name in names) { Console.WriteLine(name); } Console.ReadKey(); } |
C# While Loop Equivalent
1 2 3 4 5 6 7 8 9 10 11 12 13 | static void Main(string[] args) { var names = new List<string>() { "John", "Tom", "Peter" }; var enumerator = names.GetEnumerator(); while (enumerator.MoveNext()) { string name = (string)enumerator.Current; Console.WriteLine(name); } Console.ReadKey(); } |