Break and Continue
In the context of loops, there are two important words: break and continue. We have already briefly mentioned break, but not in detail. Let’s take a closer look at Break and Continue in this article.
The easiest way to demonstrate this is by using a For loop.
Example of break in CSharp
class Program { static void Main(string[] args) { for (int counter = 0; counter < 10; counter++){ Console.WriteLine(counter); if (counter == 3) { Console.WriteLine("On 3 everyone is on the tree"); break; } } Console.Read(); } }
Break causes that our pointer exits from the loop . In this case, we use a For loop, but it works the same for other loops. We therefore receive the following output:
0
1
2
3
On 3 everyone is on the tree
In this case, it is quite easy to see that the loop is stopped at 3, but for a more complex program, it would not be 3 but a state caused by the program, or by the user (e.g., stopping the input)
Example of Continue in CSharp:
class Program { static void Main(string[] args) { for (int counter = 0; counter < 10; counter++){ Console.WriteLine(counter); if (counter == 3) { Console.WriteLine("You can read this"); continue; Console.WriteLine("But you never will read that"); } } Console.Read(); } }
So we get the following output:
0
1
2
3
You can read this
4
5
6
7
8
9
As you see, even though we have the following code:
Console.WriteLine("But you never will read that");
within our loop, it is never executed. Thats due to the use of continue. It simply says, stop running this particular run of the loop and go to the next one. So we are at 3 and the if condition is met, but after we write our first line, we jump to the next run of the loop which gives us the output 4.
Now you have seen how break and continue can be used in CSharp. Try it for yourself in order to get some experience with it.