Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

The switch statement is unlike the if-statement. It requires that each case be constant. This constraint allows various optimizations in the lower-level intermediate representation. Some optimizations are jump tables and, for strings, Dictionary collections. Switch speeds up certain parts of your C# program.
The problem with switch statements is essentially that of duplication. Often you find the same switch statement scattered around a program in different places. If you add a new clause to the switch, you have to find all these switch statements and change them. Fowler & Beck, p. 82
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. We switch on an int here.
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
5Next, we see an example of the switch statement that includes curly brackets and the default case. The program accepts an int from the user and then tests it for six different values. You see how the curly brackets { } can be used in the switch cases, and how you can combine the case statements.
Program that uses int switch [C#]
class Program
{
static void Main()
{
while (true)
{
System.Console.WriteLine("Type number and press Return");
try
{
int i = int.Parse(System.Console.ReadLine());
switch (i)
{
case 0:
case 1:
case 2:
{
System.Console.WriteLine("Low number");
break;
}
case 3:
case 4:
case 5:
{
System.Console.WriteLine("Medium number");
break;
}
default:
{
System.Console.WriteLine("Other number");
break;
}
}
}
catch
{
}
}
}
}
Output
1. Input from console application is parsed.
2. Switch statement selects a case based on input.It is possible to switch on integers or other value types, such as enums or chars. We cover these value type switches in some detail. Strings are a reference type, but the C# compiler can handle switches on strings as well.
Switch Char, Conditional Character Test Switch Enum String Switch Examples
Here we 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.
Case Example Goto Switch UsageYou 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. We demonstrate that nesting switches can actually yield good performance over other approaches.
Nested Switch Statement
One of the most common ways you can use switch to improve programs is when you have a method that must return a different value based on a small range of inputs. Method1 uses a switch statement, while Method2 uses a series of if-statements. The benchmark shows that the switch statement version is slightly faster.
Program that benchmarks switch [C#]
using System;
using System.Diagnostics;
class Program
{
static int Method1(int v)
{
switch (v)
{
case 0:
return 10;
case 1:
return -1;
case 2:
return 20;
default:
return 0;
}
}
static int Method2(int v)
{
if (v == 0) return 10;
if (v == 1) return -1;
if (v == 2) return 20;
return 0;
}
static void Main()
{
Method1(0); Method2(0);
const int max = 100000000;
var s1 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
Method1(0);
Method1(1);
Method1(2);
Method1(3);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
Method2(0);
Method2(1);
Method2(2);
Method2(3);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.Read();
}
}
Results
9.25 ns [switch]
9.85 ns [if]Performance overview. 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. We provide benchmarks of the switch statement.
If Versus Switch Performance Regex Versus Loop
Intermediate language. The switch statement is often implemented at a lower level with the switch opcode. You can see an example of this opcode on this site.
switch Instruction
Using a switch statement on an int value is one of the best uses for switch, as it can yield improved performance. Additionally, the switch can impart improved symmetry to a selection statement, because the cases must have constant values. String switches can also be beneficial to performance in the C# programming language.