C# Switch Overview

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.

Switch introduction

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

5

Switch on values

It 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 Enum and Int.

See Switch Char, Conditional Character Test.

Switch on strings

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.

See String Switch Examples.

Performance of switch

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 Switch Slower Than If.

See Validate Characters in String.

Nesting switches

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.

See Nested Switch Statement.

Switch syntax

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.

See Case Example.

See Goto Switch Usage.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen