Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
1.5k views
in Blog Post by 48 54 94
edited by

In this post, we will explain the difference between the jumping statement break and continue in C#.

Break in C#

  • The break is a "jump out" statement that completely exits the loop iteration.
  • You can see the break statement in loops such as 
    • For Loop,
    • Foreach Loop,
    • While Loop,
    • Do while Loop and 
    • Switch Case.
  • Break in the nested loop is used to terminate the inner nested loop, and return control to the outer loop.

 Ex: 

Break statement in Loops

In the following example, the break statement will terminate the loop when i=2.

for (int i = 0; i < 5; i++)
{
  if (i == 2)
  {
    break;
  }
  Console.WriteLine(i);
}

The output will be

0
1

Break statement in switch

  • The break statement used in switch case to terminate the switch case and prevent continuing in the other subsequent cases.
  • If there is no break in switch case all cases will run till the closing " }".

Ex:

int i=3
switch(i)
{
  case 1:
       Console.Writeline("one");
       break;
  case 2:
       Console.Writeline("two");
    break;
  case 3:
       Console.Writeline("three"); 
       break;
  default:
         Console.Writeline("no match");
         break;
} // the output will be "three"

Continue in C#

Continue is an example of a "jump out" statement that skips only the current iteration execution.

EX:

In the following example, the continue statement will terminate the loop only when i=2 and complete the loop.

 for (i = 0; i <= 5; i++)
          { 
              if (i == 2)                             
                  continue;
             Console.WriteLine("value is"  +i);            
          } 

The output will be

0
1
3
4
5

Using both break and continue in for loop

In the following example, the continue statement will skip code when i=2 only and the break statement will terminate the loop when i=4.

 for (i = 0; i <= 5; i++)
          { 
              if (i == 2)                             
                  continue;
              if (i == 4)              
                  break; 
              Console.WriteLine("value is"  +i);            
          } 

The output will be

0
1
3

Conclusion

In this post, we have explored the difference between break and continue statement in c#.

See Also


1.1k questions

679 answers

459 comments

193k users

تعلم بالعربي PowerApps

تعلم بالعربي Power Automate

If you don’t ask, the answer is always NO!
...