Break Statement

C#C# break statement is used to break a loop.  In some cases, at certain point you want to break a loop and want to stop the execution when you find the exact match as per your requirement.  In such cases, you can make use of break statement.  Let me elaborate it a bit more, suppose you have bunch of names in a collection object and you want to print all names until the loop reach to a specific name.  In that case, you can make use of break statement to break the loop and proceed with further code execution process.  The C# sample code is given below demonstrating the above given example.

using System;

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

            foreach (string name in names)
            {                

                if (name == "Albert")
                {
                    break;
                }

                Console.WriteLine(name);
            }

        }
    }
}

 

Output:

Robert
Press any key to continue . . .