c# .net

How to jump out of foreach with break statement in C#?

How to jump out of foreach with break statement in C#?, someone asked me to explain?

The following example shows how to break out of a foreach statement in c#. If break statement is used within the loop body, it stops the loop iterations and goes immediately after the loop body.

 

static void Main(string[] args)
        {
            try
            {
                var names = new List<string>() { "Car", "Bike", "Bus" };
                foreach (string name in names)
               {
                   if (name == "Bike")
                   {
                       break;
                   }
                   Console.WriteLine(name);
               }


            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

Output:

Car

Post your comments / questions