If I write a for, do, or while loop, is it possible to come out of this with the return keyword?
Eg:
class BreakTest { public static void Main() { for (int i = 1; i <= 100; i++) { if (i == 5) **return;** Console.WriteLine(i); } } }
I know return can be used to exit if statements so I am curious about this as I have never tried it (and can't access my software to write the code to test this).
break is used to end a loop prematurely while return is the keyword used to pass back a return value to the caller of the function. If it is used without an argument it simply ends the function and returns to where the code was executing previously.
Tips. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.
Yes, returning early is normally preferred rather than having to finish iterating over the entire collection when it's not needed, unless there's something else going on that warrants a complete iteration (finding the minimum/maximum value, etc.)
return
will exit the current method (Main in your example). Use break
to exit the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With