C# foreach Loop

Updated on     Kisan Patel

The foreach loop enables you to iterate over each element of an array or each element of a collection.

The basic structure of a foreach loop is-

foreach(<type of elements in array/collection> in <array/collection>) {
     statement or block of code
}

Lets take an example how foreach loop iterate each element in an array.

using System;

namespace ConsoleApp
{
    class foreachDemo
    {
        static void Main(string[] args)
        {
            string[] names = {"Kisan", "Ravi", "Devang", "Ujas" };

            foreach(string name in names) {
                Console.WriteLine(name);
            }
        }
    }
}

The output of the above C# program…

c-sharp-foreach-demo


C#

Leave a Reply