foreach
suggest changeforeach
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”
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,
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents