C# Switch

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

Switch

Switch. Sometimes we need a change in life. Monotony builds. One thing happens after another. This calls for the switch statement.


Concept

A switch decides. It tests a variable against a set of constants. And the compiler uses lookup table optimizations. Switches are sometimes faster.


Piece of computer software: a program

This program uses a switch. It introduces an int local. It tests the "value" variable against two constants: 1 and 5. As it equals 5, we reach the second case. And 5 is printed.

Int

Caution:Not every variable can be used in a switch. Most built-in value types, like int or char, work.

And:Strings can be switched upon.
These are implemented in a different way.
They use a hidden Dictionary.

Based on:

.NET 4.5

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

5

Steps

Another example. This includes curly brackets and the default case. The program accepts an int from the user (with ReadLine). It then tests it for six values.

Here:We see how the curly brackets are used in the switch cases. And we combine some of 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.

Int

Types. It is possible to switch on integers or other value types, such as enums or chars. Strings are a reference type, but the C# compiler can handle switches on strings as well.

Switch CharSwitch EnumSwitch String
Case

Syntax. We cover switch syntax. The switch statement uses somewhat different indentation rules by default. Some cases (default) do not use the case keyword.

Case

Goto:We can use goto statements in switches.
These are different from other gotos.

Goto Switch

Nesting:We can put most anything inside the case block of a switch, including other switches. This quickly becomes complex.

Nested Switch

Caution:The C# language allows us to use deeply-nested switches with many embedded goto statements. But it does not encourage this.


Break keyword

The break keyword is used within switches. And continue may also be used. These two keywords are used also within loops. Sometimes they are used in both loop and switch statements.

BreakContinue

So:Are you breaking out of a switch, or out of the enclosing loop? Scope is important: the deepest construct is broken first.


Performance optimization

Benchmark. A switch statement helps optimize some programs. Suppose a method that must return a value based on a small range of inputs. You can use switch to test these values.

Here:Method 1 uses a switch statement.
But method 2 instead uses a series of if-statements.

Note:The benchmark shows that the switch statement version is slightly faster. Those nanoseconds may come in handy someday.

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

Speed. Switch can be implemented with a jump table in the intermediate language. Large switches can be much faster than long series of if-else statements. We provide more benchmarks.

1. If and switch.The if-statement sometimes performs better than the switch. Testing is essential.

If, Switch Comparison

2. Regex and switch.The switch statement can be used to replace a Regex method call. This can make programs much faster.

Regex, Switch

3. Intermediate language:Switch is often implemented at a lower level with the switch opcode. We show an example.

switch Instruction
Virtual keyword

Usage. Should we use switches everywhere? This is probably a bad idea. With polymorphism, we abstract selections with virtual methods and inheritance. This leads to cleaner code.

Virtual

So:If you want to use switches everywhere in your code, go ahead. But don't expect to be admired for it.


Refactoring

Refactoring. We consider a quote from the book Refactoring, an excellent treatise on how to improve code so it is not terrible. Well-designed code is easier to maintain.

Refactoring

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


Switch

I like switch statements. They often outperform if-statements. But more importantly, they help with code design. They enforce all values tested are constants.


Symmetry. This imparts a greater sense of symmetry. Switches test value types and strings. They speed up selections. And with them, we write clearer code.

C#