foreach

suggest change

foreach is used to iterate over the elements of an array or the items within a collection which implements IEnumerable✝.

var lines = new string[] { 
    "Hello world!", 
    "How are you doing today?", 
    "Goodbye"
};

foreach (string line in lines)
{
    Console.WriteLine(line);
}

This will output

“Hello world!” “How are you doing today?” “Goodbye”

Live Demo on .NET Fiddle

You can exit the foreach loop at any point by using the break keyword or move on to the next iteration using the continue keyword.

var numbers = new int[] {1, 2, 3, 4, 5, 6};

foreach (var number in numbers)
{
    // Skip if 2
    if (number == 2)
        continue;

    // Stop iteration if 5
    if (number == 5)
        break;

    Console.Write(number + ", ");
}

// Prints: 1, 3, 4,

Live Demo on .NET Fiddle

Notice that the order of iteration is guaranteed only for certain collections such as arrays and List, but not guaranteed for many other collections.

✝ While IEnumerable is typically used to indicate enumerable collections, foreach only requires that the collection expose publicly the object GetEnumerator() method, which should return an object that exposes the bool MoveNext() method and the object Current { get; } property.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Keywords:
* as
* goto
* break
* const
* for
* is
* fixed
* sealed
* typeof
* this
* foreach
* void
* char
* params
* base
* string
* null
* return
* while
* using
* ulong
* uint
* unsafe
* int
* var
* lock
* where
* extern
* switch
* when
* struct
* static
* do
* bool
* long
* sizeof
* in
* enum
* ushort
* sbyte
* event

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
51 Keywords
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script