Foreach Loop

C#C# foreach loop basically used for an iteration purpose.  In that iteration process, we loop through an collection object and display or manipulate the each object in that collection based upon our requirements.  For example, if you have an object like an array which contains bunch of names and  you want to display all the names to the end user, you can make use of foreach loop.  The C# sample code is given below.

using System;

namespace MyHelloWorld
{   
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Robert", "Albert", "Mark" };

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

        }
    }
}

 

 Output:

Robert
Albert
Mark
Press any key to continue . . .