The switch statement in the C# language offers a control structure that has various optimizations in the lower-level intermediate representation, from jump tables to Dictionary structures for string switch. It is important for code tuning, and we describe its usage here in these articles.
To start, this program demonstrates the syntax of a simple switch statement in the C# language. It does not show all the features of switch statements, but reveals the core concept of a selection statement based on constant case values.
--- Program that uses switch [C#] ---
using System;
class Program
{
static void Main()
{
int value = 5;
switch (value)
{
case 1:
Console.WriteLine(1);
break;
case 5:
Console.WriteLine(5);
break;
}
}
}
--- Output of the program ---
5It is possible to switch on integers or other value types, such as enums or chars. These two articles cover these value type switches in some detail.
See Switch Char, Conditional Character Test.
The C# language also provides a way for you to switch on strings directly: this can result in optimized code versus a long series of if-else if statements. This article demonstrates the use of string switches.
The big deal with switch is that it can be implemented with a jump table in the intermediate language. This means that large switches can be much faster than long series of if-else if statements. These articles provide benchmarks of the switch statement.
See If Versus Switch Performance.
See Validate Characters in String.
You can put most anything inside the case block of a switch, including other switches! This means you can nest switches as deeply as you wish. This article demonstrates that nesting switches can actually yield good performance over other approaches.
There are two articles here that elaborate on specific aspects of the switch construct's syntax. The switch statement uses somewhat different indentation rules by default in the C# language. Also, we describe how you can use goto statements in switches.