foreach, in (C# Reference)
This page is specific to:.NET Framework Version:
C# Language Reference
foreach, in (C# Reference)

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections..::.IEnumerable or System.Collections.Generic..::.IEnumerable<(Of <(T>)>) interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.

At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.

A foreach loop can also be exited by the goto, return, or throwstatements.

For more information about the foreach keyword and code samples, see the following topics:

Using foreach with Arrays (C# Programming Guide)

How to: Access a Collection Class with foreach (C# Programming Guide)

Example

In this example, foreach is used to display the contents of an array of integers.

class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
        foreach (int i in fibarray)
        {
            System.Console.WriteLine(i);
        }
    }
}
/*
Output:
0
1
2
3
5
8
13
*/



C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 5.3.3.16 Foreach statements

  • 8.8.4 The foreach statement

See Also

Concepts

Reference

Other Resources

Community Content

foreach will throw an exception if enumeration is null
Added by:AristosQueue

If the enumeration you are looping over is null, foreach will throw an exception. Thus you may need an if-test to check for a null enumeration before doing your foreach loop.

    if (null != fibarray) // if you are not certain that fibarray is allocated...
{
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
© 2010 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View