The break statement terminates the closest enclosing loop or conditional statement in which it appears. Control is passed to the statement that follows the terminated statement, if any. The break statement takes the form:
break;
In this example, the conditional statement contains a counter that is supposed to count from 1 to 100; however, the break statement terminates the loop after 4 counts.
using System; class BreakTest { public static void Main() { for (int i = 1; i <= 100; i++) { if (i == 5) break; Console.WriteLine(i); } } }
1 2 3 4
This example demonstrates the use of break in a switch statement.
// break and switch using System; using System.IO; class Switch { public static void Main() { Console.Write("Enter your selection (1, 2, or 3): "); string s = Console.ReadLine(); int n = Int32.FromString(s); switch(n) { case 1: Console.WriteLine("Current value is {0}", 1); break; case 2: Console.WriteLine("Current value is {0}", 2); break; case 3: Console.WriteLine("Current value is {0}", 3); break; default: Console.WriteLine("Sorry, invalid selection."); } } }
Run #1:
Enter your selection (1, 2, or 3): 2 Current value is 2
Run #2:
Enter your selection (1, 2, or 3): 4 Sorry, invalid selection.
C# Keywords | Compare to C++ | switch | Jump Statements | Grammar