Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
C# Reference
C# Keywords
Statement Types
 foreach, in
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:

Want more? Here are some additional resources on this topic:

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. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

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 using the break keyword, or step directly 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 on 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)

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

// cs_foreach.cs
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

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

  • 5.3.3.16 Foreach statements

  • 8.8.4 The foreach statement

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
ERROR      delpiero5   |   Edit   |  

foreach (int daysInMonth in DaysInMonths)
{
if (dayNum <= daysInMonth)
{
break;
}
else
{
dayNum -= daysInMonth;
monthNum++;
}


}

Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker