IL switch Instruction

Switch illustration

The switch instruction is implemented with a jump table. The switch keyword—in the C# language—is typically (but not always) compiled to a switch instruction. Switch often improves performance.

This .NET IL article shows the switch instruction. It shows how C# programs that use switch are compiled.

Switch instruction

The C# version of the program uses a switch with three cases. The cases 0, 1 and 2 are used. In the intermediate language, we can see the instruction switch (IL_0020, IL_0027, IL_002e). Those three identifiers point to lines, which are also underlined in the example below.

Program that uses switch statement [C#]

using System;

class Program
{
    static void Main()
    {
	int i = int.Parse("1");
	switch (i)
	{
	    case 0:
		Console.WriteLine(0);
		break;
	    case 1:
		Console.WriteLine(1);
		break;
	    case 2:
		Console.WriteLine(2);
		break;
	}
    }
}

Intermediate language

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       53 (0x35)
  .maxstack  1
  .locals init ([0] int32 i,
	   [1] int32 CS$0$0000)
  IL_0000:  ldstr      "1"
  IL_0005:  call       int32 [mscorlib]System.Int32::Parse(string)
  IL_000a:  stloc.0
  IL_000b:  ldloc.0
  IL_000c:  stloc.1
  IL_000d:  ldloc.1
  IL_000e:  switch     (
			IL_0020,
			IL_0027,
			IL_002e)
  IL_001f:  ret
  IL_0020:  ldc.i4.0
  IL_0021:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0026:  ret
  IL_0027:  ldc.i4.1
  IL_0028:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_002d:  ret
  IL_002e:  ldc.i4.2
  IL_002f:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0034:  ret
} // end of method Program::Main

How it works. The switch instruction pops the top value from the evaluation stack. In the program, we have three cases, which happen to be 0, 1 and 2. The switch instruction has three arguments, and these also happen to be indexed by the values 0, 1 and 2. So if the popped value was 0, we go to IL_0020; if it was 1, we go to IL_0027; if it was 2, we go to IL_002e. Those identifiers are themselves implemented as offsets to the correct location.

Ret

Question and answer

Why does the program use a ret instruction after each jump location in the switch statement? Ret is used instead of another type of branch statement because there are no further instructions in the program.

ret Instruction

Summary

We looked at a very simple example of the switch instruction in the intermediate language, which all C# and VB.NET programs are compiled to. It is possible for compilers to translate certain if-statements into switches and vice-versa.

Intermediate Language
.NET