enumerables can be iterated over using a foreach
loop:
char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };
foreach (char vowel in vowels)
{
// Output the vowel
System.Console.Write(vowel);
}
// => aeiou
A foreach
loop consists of three parts:
However, generally a foreach
loop is preferrable over a for
loop for the following reasons:
foreach
loop is guaranteed to iterate over all values. With a for
loop, it is easy to miss elements, for example due to an off-by-one error.foreach
loop is more declarative, your code is communicating what you want it to do, instead of a for
loop that communicates how you want to do it.foreach
loop is foolproof, whereas with for
loops it is easy to have an off-by-one error.foreach
loop works on all collection types, including those that don't support using an indexer to access elements.To guarantee that a foreach
loop will iterate over all values, the compiler will not allow updating of a collection within a foreach
loop:
char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };
foreach (char vowel in vowels)
{
// This would result in a compiler error
// vowel = 'Y';
}
A for
loop does have some advantages over a foreach
loop:
for
loops in scenarios that don't involve collections.Related Topics:
int[,] arr = new int[10, 5]
which can be very useful.System.Array
with Array.CreateInstance
. Such objects are of little use - mainly for interop with VB.NET code. They are not interchangeable with standard arrays (T[]
). They can have a non-zero lower bound.Both the above topics are discussed more fully in a later exercise.