C# Foreach Loop Examples

Dot Net Perls
Foreach loop construct

Keeping track of index values in loops is challenging. With the foreach-loop in the C# language, we don't need to. We use foreach, as demonstrated here, to enumerate the individual values in collections with less complex syntax than the traditional for-loop—this eliminates bugs caused by incorrect index variables.

Key points: Foreach has the simplest syntax of all loops. It is used in some constructs such as enumerators and query expressions. It is recommended in most program contexts.

Example

This example shows how you can use the keyword foreach on a string array in a C# program to loop through the elements in the array. In the foreach-statement, you do not need to specify the loop bounds minimum or maximum, and do not need an 'i' variable as in for-loops. This results in fewer characters to type and code that it is easier to review and verify, with no functionality loss.

Program that uses foreach over array [C#]

using System;

class Program
{
    static void Main()
    {
	// Use a string array to loop over.
	string[] ferns =
	{
	    "Psilotopsida",
	    "Equisetopsida",
	    "Marattiopsida",
	    "Polypodiopsida"
	};
	// Loop with the foreach keyword.
	foreach (string value in ferns)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

Psilotopsida
Equisetopsida
Marattiopsida
Polypodiopsida

Syntax. The foreach-statement contains the reserved "foreach" keyword followed by a parenthetical containing the declaration of the iteration variable. The iteration variable "string value" can be a different type such as "int number" if you are looping over that type. You must specify the keyword 'in' and then the object to loop over. You can use a List, Dictionary, ArrayList, custom collections, or any type of array to loop over.

LINQ query example

LINQ (language integrated query)

This example uses the foreach-loop statement but that evaluates a LINQ expression that sorts an array. The LINQ extension to the C# language provides queries that are evaluated lazily, which means that the sorting in the example won't occur until the foreach loop is executed.

Program that uses foreach with LINQ query [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// An unsorted string array.
	string[] letters = { "d", "c", "a", "b" };
	// Use LINQ query syntax to sort the array alphabetically.
	var sorted = from letter in letters
		     orderby letter
		     select letter;
	// Loop with the foreach keyword.
	foreach (string value in sorted)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

a
b
c
d

Query expression evaluation. With the LINQ extensions to the C# language, the foreach keyword is critical because it provides a greater level of abstraction over loop enumeration than a for-loop with an induction variable. Trying to use LINQ without the foreach keyword is frustrating and much more difficult.

Foreach var loop

Var keyword

Using the var keyword in foreach loops is not in many examples and can really simplify your loop syntax. Let's compare a foreach loop with the var keyword used in the enumeration statement, with a standard foreach loop. The example enumerates a Dictionary. You can see how the characters count in "KeyValuePair" can be reduced.

Var Examples KeyValuePair Hints Dictionary Examples
Program that uses foreach var loop [C#]

using System;
using System.Collections.Generic;

class Program
{
    static Dictionary<int, int> _f = new Dictionary<int, int>();

    static void Main()
    {
	// Add items to dictionary.
	_f.Add(1, 2);
	_f.Add(2, 3);
	_f.Add(3, 4);

	// Use var in foreach loop.
	foreach (var pair in _f)
	{
	    Console.WriteLine("{0},{1}", pair.Key, pair.Value);
	}
    }
}

Output

1,2
2,3
3,4

Program that uses foreach loop [C#]

using System;
using System.Collections.Generic;

class Program
{
    static Dictionary<int, int> _h = new Dictionary<int, int>();

    static void Main()
    {
	// Add items to dictionary.
	_h.Add(5, 4);
	_h.Add(4, 3);
	_h.Add(2, 1);

	// Standard foreach loop.
	foreach (KeyValuePair<int, int> pair in _h)
	{
	    Console.WriteLine("{0},{1}", pair.Key, pair.Value);
	}
    }
}

Output

5,4
4,3
2,1

First loop. Here we see how you can use var in the foreach loop. The var actually is of type KeyValuePair<int, int>. You can see how specifying the entire generic name could make code less clear. Additionally, the var keyword here substitutes for a type that never actually appears in the program.

Second loop. Here we see the standard foreach syntax. The enumeration variable is fully specified. The syntax of the foreach conditional is much longer. The more text and symbols you have to read, the more likely you will have to deal with a typo in your code.

Foreach List example

List type.

Continuing on, we see how you can loop through the elements in a List generic collection. The foreach loop construct provides a way to elegantly loop through elements, but it has the drawback of restricting any mutations made to the collection during the loop.

Program description. We use the foreach-loop construct to loop over each element in the List variable. You can see in the output section that all the integers are printed to the screen. After this, we try calling the Remove method on the List variable inside a foreach-loop over the list: this fails because of a restriction of the foreach-loop.

Program that uses list and foreach loop [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<int> list = new List<int>();
	list.Add(1);
	list.Add(2);
	list.Add(3);
	// Loop over list elements using foreach loop.
	foreach (int element in list)
	{
	    Console.WriteLine(element);
	}
	// You can't remove elements in a foreach loop.
	try
	{
	    foreach (int element in list)
	    {
		list.Remove(element);
	    }
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex.Message);
	}
    }
}

Output

1
2
3
Collection was modified; enumeration operation may not execute.
Question and answer

Why can't you modify elements inside foreach? The reason you cannot remove elements inside a foreach-loop is the looping mechanism requires that state be saved. The runtime cannot tell if you removed an element that was to be looped over in a subsequent iteration. Obviously, if you remove elements that are already looped over, this wouldn't cause any problems, but the runtime disallows this because this case cannot be detected easily.

InvalidOperationException: Collection Was Modified

Summary. The foreach loop construct on the List type provides an elegant and simple way to loop over all elements in the collection. It has a limitation that you cannot change the layout of the collection during the loop, however. If you want to add or remove elements during a loop, you could use a for-loop construct—but be careful to maintain correct indexes.

For-loop and foreach-loop

For loop

Here we compare an example loop with the keyword for and an example loop with the keyword foreach. The code that follows illustrates the exact difference between the two loop constructs. You can see that the for-loop has more complexity in its syntax, but this also gives it more power if you want to modify the collection or examine adjacent elements in the array.

Program that uses for-loop and foreach-loop [C#]

using System;

class Program
{
    static void Main()
    {
	// Array of rabbits names.
	string[] rabbits =
	{
	    "Forest Rabbit",
	    "Dice's Cottontail",
	    "Brush Rabbit",
	    "San Jose Brush Rabbit"
	};

	// Loop through string array with a for loop.
	for (int i = 0; i < rabbits.Length; i++)
	{
	    // Assign string reference based on induction variable.
	    string value = rabbits[i];
	    Console.WriteLine(value); // Write the value.
	}

	// Loop through the string array with a foreach loop.
	foreach (var value in rabbits)
	{
	    Console.WriteLine(value); // Write the value.
	}
    }
}

Output

Forest Rabbit
Dice's Cottontail
Brush Rabbit
San Jose Brush Rabbit
(... Repeated.)

Affine and induction variables. Optimizing compilers such as the C# compiler do interesting static analysis on loop variables in for-loops, because the speed of loops is critical in many programs. In compiler theory, an expression that is based on a loop index such as 'i' is called an affine expression and the loop iteration variables are considered induction variables. The compiler then uses strength reduction techniques to transform slow multiplications into fast additions.

Dragon Book (Compilers)

Compile-time error

This is a warning

A compile-time error is caused when you try to compile a program that uses a foreach iteration variable in an incorrect way. Foreach variables are essentially read-only variables, and the C# compiler uses static analysis to detect this kind of error before it ever causes a problem in your program. If you want to change the data in a loop, using a for-loop is often a better choice. With a for-loop, you can use the loop induction variable to assign elements directly.

Error 1 Cannot assign to 'value' because it is a 'foreach iteration variable'

Performance

Performance optimization

There are performance issues with the foreach-loop versus the for-loop. The foreach-loop has at best equivalent but not better performance in regular looping conditions than the for-loop. Sometimes the foreach-loop can be used in a way that you cannot use a for-loop, such as with the yield keyword, which can enhance performance by delaying or avoiding computations.

For Loops

Tip: I suggest you prefer the foreach-loop when writing less important parts of programs, as it reduces the complexity of the notation, but prefer the for-loop for hot loops as a precaution.

Examples

Note (please read)

There are many other examples of how you can use foreach-loops in your C# programs. This site contains examples for many loops over many types of collections, and this next section lists and describes some of the most useful articles on this subject.

Loop Over String Array Loop Over String Chars In Keyword

GetEnumerator

When designing a collection that is likely to be widely used throughout other code, you can implement the GetEnumerator method to enable the foreach loop to automatically be able to loop over the data in your collection. This is implemented in the framework collections in System.Collections.Generic, for example.

Yield keyword

Yield keyword

There is a powerful feature in the C# language that gives you a way to declare enumerators with a shorthand syntax. This feature is the keyword yield, which is combined with the break and return keywords to provide a way to re-enter a function in its body. The C# compiler generates a lot of code when you use yield. The keyword yield is contextual, which means it is used to provide this function when the compiler thinks that is the program's intention.

Yield Return Example

Summary

The C# programming language

We saw examples of using foreach-loops in the C# language, first seeing an example of looping over an array; an example of the foreach-loop with a LINQ expression; a comparison of the for-loop and foreach-loop; and a compile-time error with the foreach-loop. We noted performance issues with the foreach-loop construct. Finally, we mentioned compiler theory and how it relates to loop optimization.

Loop Constructs