C# Console

Foreach Examples in C#

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.

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.

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.

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

C# While Loop Equivalent

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.