TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Break Statement: Foreach and Switch

This C# example program uses the break keyword. Break stops loop and is used within switch statements.

Break, a 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.

Example. 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.

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.

C# program that uses break in loops

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]);
	    // ... See if the element has value of 15.
	    if (array[i] == 15)
	    {
		Console.WriteLine("Value found");
		break;
	    }
	}
	Console.WriteLine("--- foreach-loop and break ---");
	foreach (int value in array) // Use foreach loop
	{
	    Console.WriteLine(value);
	    // ... See if the iteration variable has value of 15.
	    if (value == 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

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.

Do

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. 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.

C# program that uses loop and switch with break

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

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

Yield. 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. 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. 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.

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.

IL

Disasters. 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.

Summary. Break effectively stopped loop iteration. 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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf