C# has a specialized iteration operator called foreach.
foreach does not loop based on a boolean expression. Rather, it executes a block of code on each element in an array or other collection.
Syntax:
foreach(type loopVariable in collection)
{
Execution steps
}
In above syntax, the life of loopVariable will be only in the foreach loop.
Since the string array is a valid collection, foreach can be used to iterate through it.
Example:
using System;
namespace forgetCode
{
class Program
{
static void Main(string[] args)
{
string[] cityNames = { "Chennai", "Mumbai", "Bangalore", "Delhi", "Trichy" };
foreach (string name in cityNames)
{
Console.WriteLine(name);
}
}
}
}
Output:
Chennai
Mumbai
Bangalore
Delhi
Trichy
..