Introduction
Break and Continue are the two words are widely used in C#.NET and it make sense as this two are most important statement in C#.They widely used in loop in C#.
Continue is used to skip the current iteration code written after continue statement and ask the compiler to continue the next iteration.
Break is used to exit the loop and will not continue the loop further.
Continue
Continue Statement in C# |
In the above Flow diagram when it reach the continue statement it skip the current iteration and execute the remaining iteration.
Lets Understand with a simple program.
class MyClass
{
public static void Main()
{
MyClass myclass = new MyClass();
myclass.Understand_Continue();
Console.ReadKey();
}
public void Understand_Continue()
{
for (int iContinue=1;iContinue<=5;iContinue++)
{
if (iContinue == 3)
continue;
Console.WriteLine(iContinue);
}
}
}
Output
Continue Statement in C# Output |
Look at the above statement Highlighted with Yellow color. This suggest that if the value iContinue=3 then the below write statement will not executed and will go back to For loop for Next iteration.
See the Output where 3 is not printed as expected.
Break
Break Statement in C# |
In the above Flow diagram when it reach the Break statement it exit the loop and will not execute the remaining iteration.
Lets Understand with a simple program.
class MyClass
{
public static void Main()
{
MyClass myclass = new MyClass();
myclass.Understand_Continue();
Console.ReadKey();
}
public void Understand_Continue()
{
for (int iBreak=1;iBreak<=5;iBreak++)
{
if (iBreak == 3)
break;
Console.WriteLine(iBreak);
}
}
}
Output
Break Statement in C# Output |
Look at the above statement Highlighted with Yellow color. This suggest that if the value iBreak=3 then the below write statement will not executed and will exit the For loop.
See the Output where 1,2 is printed and not printed the remaining values as expected.
Conclusion
- Break statement used to exit the loop where as Continue statement used to skip the current iteration and execute the remaining.
- When we want to exit the loop in middle of the execution we use Break.
- Break will work for the current loop . It will not work for the external loop if nested.
- Continue also work for the same loop , not for the external if nested loop is there.
No comments:
Post a Comment