What is break; in c#, and what purpose does it serve(Explain it to me as if i'm an idiot plz). | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

What is break; in c#, and what purpose does it serve(Explain it to me as if i'm an idiot plz).

// and can you even explain what it does in this code. int num = 0; while (num < 20) { if (num == 5) break; Console.WriteLine(num); num++; }

28th Jan 2017, 3:36 AM
Christopher
5 Answers
+ 8
In your example: The loop runs and num gets incremented for each loop, i.e. values of num increases from 0 to 1, 2, 3... When num is 5, it fulfills the if conditional statement and break is executed. What break does is to tell the program flow to "break" out of the loop which it is currently in. When the break statement is encountered, the while loop will be exited directly. Hence, num (5) will not be printed to the console because the print statement comes after the break, and is inside the while loop. The program exits the loop before num can get printed.
28th Jan 2017, 4:05 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
as long as when num is below 20, test if num is 5. If num is 5, stop the loop. else write down the value of num and add the value of num by 1 break; == exit/stop any loop
28th Jan 2017, 5:03 AM
Wen Qin
Wen Qin - avatar
+ 2
Thanks Hasty Rei, I kinda get it now. So I'll will just move on to more lessons and eventually i will pick onto it
28th Jan 2017, 5:32 AM
Christopher
0
break; basically jumps out of the loop, in this case, the while loop. this can be put in other loops like for loops etc.
28th Jan 2017, 3:42 AM
Dawzy
Dawzy - avatar
0
Okay, if you don't mind can you give a better example and definition of break; ,and explain step by step what break does to the code.
28th Jan 2017, 4:01 AM
Christopher