Jump to content
Wikibooks The Free Textbook Project

C# Programming/Keywords/break

From Wikibooks, open books for an open world
The latest reviewed version was checked on 16 April 2020. There are template/file changes awaiting review.

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

break as used in a loop
intx;

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
intx;
switch(x)
{
case0:
Console.WriteLine("x is 0");
break;
case1:
Console.WriteLine("x is 1");
break;
case2:
// falls through
case3:
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
Special C# Identifiers (Contextual Keywords)
Contextual Keywords (Used in Queries)

AltStyle によって変換されたページ (->オリジナル) /