Today, in this blog I will show you the foreach loop in C# language and how to use this loop in c#.

What is a foreach loop in C#?

Syntax of foreach loop

foreach (string name in array)
{
}

Example

class Program

{

static void Main(string[] args)

{

string[] array = new string[5]; // declaring array

//Storing value in array element

array[0] = "Ehtesham";

array[1] = "Raza";

array[2] = "Zaid";

array[3] = "Salman";

array[4] = "Zaryab";

//retrieving value using foreach loop

foreach (string name in array)

{

Console.WriteLine("Hy Whats up " + name);

}

Console.ReadLine();

}

}

Output

Hy Whats up Ehtesham
Hy Whats up Raza
Hy Whats up Zaid
Hy Whats up Salman
Hy Whats up Zaryab

Note - We can use any type of data type in the foreach loop syntax like var, int etc.