C# Break

Break keyword

The break keyword alters control flow. It has subtle yet important differences depending on its context. Break statements are used in certain parts of a program.
We use them in for-loops,
foreach-loops
and switch statements.

Keywords

Loop

First, this example shows the reserved break keyword in the for-loop and foreach-loop constructs. Please note that you cannot use the word "break" as a variable identifier. It is reserved. You can prefix it with a @ symbol such as @break.

ForForeachKeyword: keywords direct program behavior

Break:During execution, the intermediate language corresponding to the break statement is encountered in the program's assembly.

And:Control is immediately transferred to the statement following the enclosing block.

Program that uses break in loops: C#

using System;

class Program
{
    static void Main()
    {
	// Array.
	int[] array = { 5, 10, 15, 20, 25 };
	Console.WriteLine("--- for-loop and break ---");

	// Loop through indexes in the array.
	for (int i = 0; i < array.Length; i++)
	{
	    Console.WriteLine(array[i]);
	    if (array[i] == 15) // See if the element has value of 15.
	    {
		Console.WriteLine("Value found");
		break;
	    }
	}
	Console.WriteLine("--- foreach-loop and break ---");
	foreach (int value in array) // Use foreach loop
	{
	    Console.WriteLine(value);
	    if (value == 15) // See if the iteration variable has value of 15.
	    {
		Console.WriteLine("Value found");
		break;
	    }
	}
    }
}

Output

--- for-loop and break ---
5
10
15
Value found
--- foreach-loop and break ---
5
10
15
Value found
Loop

The example program above uses the for-loop and foreach-loop constructs. The break keyword is often more useful in the while-loop. Internally, some of these loops are interchangeable.

And:If you disassemble your program you will often find that there is no difference between for, while and do-while.

DoReturn keyword

Continue/return. The C# language also includes the continue and return keywords that transfer instruction control flow. You can think of the break keyword as a local loop return statement.

Tip:If you find too many control statements like break, you may benefit from extracting logic into method and using the returns instead.

MethodsReturn

Switch

C# programming language

The C# language also allows the break keyword in the switch statement. This unfortunately leads to lots of problems in programs and has for many years through other programming languages.

Switch

When break is encountered in a switch statement, the switch statement itself is exited—but not the enclosing block. In this example the for-loop continues through all five iterations.

Program that uses loop and switch with break: C#

using System;

class Program
{
    static void Main()
    {
	for (int i = 0; i < 5; i++) // Loop through five numbers.
	{
	    switch (i) // Use loop index as switch expression.
	    {
		case 0:
		case 1:
		case 2:
		    {
			Console.WriteLine("First three");
			break;
		    }
		case 3:
		case 4:
		    {
			Console.WriteLine("Last two");
			break;
		    }
	    }
	}
    }
}

Output

First three
First three
First three
Last two
Last two
Program icon

The example program shows how the switch statement can confuse your loop code. In some cases, you would do better to put the switch statement itself in a method with a result value.

Alternatively, you can employ object-level polymorphism. This calls different methods based on a virtual dispatch table depending on the value of the switch evaluation. Try an abstract class.

Abstract Keyword

Yield

Yield keyword

The C# language also includes a yield break statement. This is a way to specify that the compiler generate code that terminates the method from being called again after it returns.

In this sense, the yield break statement is more final than the yield return statement. Yield and its implementation is not at the level of the MSIL instructions or the CLR itself. It is instead implemented in the C# compiler.

Yield

Continue

Continue

The continue keyword stops the current iteration and progresses to the next iteration of the loop. After it is encountered, the loop will execute no more remaining statements in that iteration. It will continue to the next as normal.

Continue

However:The continue statement complicates certain loop structures. In loops, as in methods, having one entry and one exit has advantages.

Research

Expert .NET 2.0 IL Assembler

You can learn the most subtle details of the break keyword and how loops are compiled. Expert .NET IL Assembler by Serge Lidin provides good documentation for understanding the abstract binary format used by the .NET Framework.

Expert .NET 2.0 IL Assembler

Info:It contains thorough descriptions of how the "br" instructions are used in the intermediate language.

Also:The specification provides an understanding of how the C# language notation expresses the logic at a higher level.

The C# Programming Language: SpecificationIL

Disasters

Warning: exclamation mark

The switch statement's traditional usage of the break keyword can cause bugs in real-world engineering projects. Mixing the switch statement in an enclosing loop has caused real-world disasters.

In the book Code Complete by Steve McConnell, it is stated that the New York City phone systems were unusable for nine hours in January 1990. This was due to a bug in code that incorrectly used the break keyword. Please see page 380.

Code Complete

Summary

We saw examples of using the keyword break in loops. We tested this keyword on the for-loop and the foreach-loop. We also looked at the switch statement's somewhat confusing usage of the break keyword.


C#: Loop