C# Programming/Keywords/break

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The keyword break is used to exit out of a loop or switch block.

break as used in a loop
int x;
 
while (x < 20){

   if (x > 10) break;

   x++;
}

The while loop would increment x as long as it was less than twenty. However when x is incremented to ten the condition in the if statement becomes true, so the break statement causes the while loop to be broken and execution would continue after the closing parentheses.

break as used in a switch block
int x;

switch (x)
    {
    case 0:
        Console.WriteLine("x is 0");
        break;
    case 1:
        Console.WriteLine("x is 1");
        break;
    case 2:
        // falls through
    case 3:
        Console.WriteLine("x is 2 or 3");
        break;
    }

When the program enters the switch block, it will search for a case statement that is true. Once it finds one, it will read any further statements printed until it finds a break statement. In the above example, if x is 0 or 1, the console will only print their respective values and then jump out of the statement. However, if the value of x is 2 or 3, the program will read the same proceeding statement(s) until it reaches a break statement. In order not to show anybody who reads the code that this handling for 2 is the same for three, it is good programming practice to add a comment like "falls through" after the falling-through cases.



C# Keywords
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
Special C# Identifiers (Contextual Keywords)
add alias async await dynamic
get global nameof partial remove
set value when where yield
Contextual Keywords (Used in Queries)
ascending by descending equals from
group in into join let
on orderby select where