C# Examples


C# Foreach Examples

Following examples show foreach loop and how it iterates over IEnumerable under the hood. You can debug examples online.

Basic Foreach Loop

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.

C# Foreach Loop


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.

C# Foreach with Continue


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.

C# Foreach with Break


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.

List (IEnumerable)

C# Foreach Loop

While Equivalent


Digging Deeper

The previous example is a little bit simplified. In fact the while equivalent to foreach also contains try-finally statement to dispose the enumerator.

Foreach over IEnumerable with Custom Implementation

Custom implementating of IEnumerable is not so easy. You have to implement interface IEnumerable (one method GetEnumerator) and interface IEnumerator (three members MoveNext, Current and Reset). The following code is almost the simpliest example of it.

C# Foreach Loop


IEnumerable / IEnumerator Implementations

Foreach over IEnumerable with "Yield Return" Implementation

Implementing IEnumerable using yield return statement is super easy. Create a method or a property with IEnumerable as the return type. Then somewhere in the method call yield return for each value you intent to have in the collection.

C# Foreach Loop

Method returning IEnumerable

See also

  • C# Foreach - how foreach and IEnumerable works debuggable online
  • C# Switch - switch statement examples debuggable online
  • C# Using - using statement examples debuggable online


By Jan Slama, 11-Jan-2016