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 |
---|
var names = new List<string>() { "John", "Tom", "Peter" };
foreach (string name in names)
{
Console.WriteLine(name);
}
|
Output |
---|
John
Tom
Peter
|
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 |
---|
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.
C# Foreach with Break |
---|
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.
List (IEnumerable) |
---|
var names = new List<string>() { "John", "Tom", "Peter" };
|
C# Foreach Loop | While Equivalent |
---|---|
foreach (string name in names)
{
Console.WriteLine(name);
}
|
var enumerator = names.GetEnumerator();
while (enumerator.MoveNext())
{
string name = (string)enumerator.Current;
Console.WriteLine(name);
}
|
Output |
---|
John
Tom
Peter
|
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 | Output |
---|---|
var trio = new Trio() {Name1 = "John", Name2 = "Tom", Name3 = "Peter"};
foreach (string name in trio)
{
Console.WriteLine(name);
}
|
John
Tom
Peter
|
IEnumerable / IEnumerator Implementations |
---|
public class Trio : IEnumerable
{
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public IEnumerator GetEnumerator() { return new TrioEnumerator(this); }
}
public class TrioEnumerator : IEnumerator
{
public TrioEnumerator(Trio trio) { _trio = trio; }
private Trio _trio;
private int _index = 0;
public void Reset() { _index = 0; Current = null; }
public object Current { get; private set; }
public bool MoveNext()
{
_index++;
/**/ if (_index == 1) { Current = _trio.Name1; return true; }
else if (_index == 2) { Current = _trio.Name2; return true; }
else if (_index == 3) { Current = _trio.Name3; return true; }
else return false;
}
}
|
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 | Output |
---|---|
foreach (string name in GetNames())
{
Console.WriteLine(name);
}
|
John
Tom
Peter
|
Method returning IEnumerable |
---|
public IEnumerable<string> GetNames()
{
yield return "John";
yield return "Tom";
yield return "Peter";
}
|
See also
- MSDN foreach, in - foreach keyword in C# Reference
- MSDN IEnumerable - IEnumerable interface
- C# Foreach - how foreach and IEnumerable works debuggable online
- C# Switch - switch statement examples debuggable online
- C# Using - using statement examples debuggable online
Tips
- [C#] String Format for DateTime – format date and time popular
- [C#] String Format for Double – format float numbers popular