Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

From the author of

break Statements

The switch statement mentioned previously showed one way to use the break statement. It allowed program control to jump out of the switch statement. Similarly, the break statement allows jumping out of any decision or loop. Its destination is always the first statement following the decision or loop.

This example shows two ways to break out of a loop:

string doAgain = "Y";

while (doAgain == "Y")
{
 Console.Write("Please Enter Site Name: ");
 siteName[count++] = Console.ReadLine();

 Console.Write("Add Another?: ");
 doAgain = Console.ReadLine();

 if (count >= 5)
 {
  break;
 }
}

Normally, a user types Y to continue or types anything else to leave. However, an array is a specified size, and it wouldn't be nice to attempt to overflow its bounds because this would cause an error. The if statement is present to guard against this happening. When the number of entries in the array exceeds its max capacity, the program breaks out of the loop with the break statement. The break statement goes to only the next level below its enclosing loop.

For Java Programmers

Java has a labeled break statement, but C# does not. In C#, whenever a jump to a label is needed, use the goto statement.

Gee, if it were necessary to jump more than one level out, it might make sense to use a goto statement. The question is, "What would be more difficult to understand: extra logic to control exit out of multiple layers of loops, or a clean jump to the end of the outermost loop?"

  • + Share This
  • 🔖 Save To Your Account