C# Break and Continue

C# Code Snippets Break and Continue
Share:

About

In this code snippet, we will take a look at break and continue in C#.

break
Is used to break out of a code block. If done in a loop it will essentially stop the loop from executing.

continue
Is used to inside a loop to skip the current iteration.

Note: break is also used with the switch statement to break out of it after a case has been matched. See how to use the switch statement here.

Let’s have a look at the code below to see how to use break and continue.

Code:

using System;

namespace BreakContinue
{
    class Program
    {
        static void Main(string[] args)
        {

            for (int i = 0; i < 10; i++)
            {
                if(i > 5)
                {
                    //break will stop the loop from looping.
                    break;
                }

                Console.Write(i + ": Hi. ");
            }

            Console.WriteLine(" ");
            Console.WriteLine(" ");

            for (int j = 0; j < 10; j++)
            {
                Console.Write(j + ": Bye ");

                if (j > 5)
                {
                    //continue won't stop the loop from looping. 
                    //It will just skip all the code after it for the current iteration.
                    continue;
                }

                Console.WriteLine("bye.");
            }

            Console.ReadLine();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger