13 Nov 2011

C# foreach loop example with string array


This example shows how you can use the keyword foreach on a string array in a C# program to loop through the elements in the array. In the foreach-statement, you do not need to specify the loop bounds minimum or maximum, and do not need an 'i' variable as in for-loops. This results in fewer characters to type and code that it is easier to review and verify, with no functionality loss.
Program that uses foreach over array [C#]

using System;

class Program
{
static void Main()
{
// Use a string array to loop over.
string[] ferns =
{
"Psilotopsida",
"Equisetopsida",
"Marattiopsida",
"Polypodiopsida"
};
// Loop with the foreach keyword.
foreach (string value in ferns)
{
Console.WriteLine(value);
}
}
}

Output

Psilotopsida
Equisetopsida
Marattiopsida
Polypodiopsida

No comments:

Post a Comment