Foreach Loop in C#

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#?

  • A foreach loop is a different kind of looping constructs in C# programming that doesn’t include initialization, termination and increment/decrement things.
  • It uses collection to take value one by one and then processes on them.
  • It eliminates errors caused by incorrect index handling.
  • At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.
  • A foreach loop can also be exited by the goto, return, or throw statements.

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.