C# Switch Enum

Switch illustration

Switch can act upon enum values. An enum switch sometimes results in clearer code. It sometimes is faster. Here we examine how you can switch on enums in the C# language.

Example

This example shows how you can use enums in switches in the C# language. Enums are useful in your program if it has to use magic constants for whatever reason. For the switch statement, look at the IsImportant method defined at the bottom of this example.

Program that switches on enum [C#]

using System;

enum Priority
{
    Zero,
    Low,
    Medium,
    Important,
    Critical
};

class Program
{
    static void Main()
    {
	// New local variable of the Priority enum type.
	Priority priority = Priority.Zero;

	// Set priority to critical on Monday.
	if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
	{
	    priority = Priority.Critical;
	}

	// Write this if the priority is important.
	if (IsImportant(priority))
	{
	    Console.WriteLine("The problem is important.");
	}

	// See if Low priority is important.
	priority = Priority.Low;
	Console.WriteLine(IsImportant(priority));

	// See if Important priority is.
	priority = Priority.Important;
	Console.WriteLine(IsImportant(priority));
    }

    static bool IsImportant(Priority priority)
    {
	// Switch on the Priority enum.
	switch (priority)
	{
	    case Priority.Low:
	    case Priority.Medium:
	    case Priority.Zero:
	    default:
		return false;
	    case Priority.Important:
	    case Priority.Critical:
		return true;
	}
    }
}

Output
    (First line is only written on Monday.)

The problem is important.
False
True
Note

Description. This program defines a custom method that contains a switch, which tests the parameter that is an enum of type Priority. It returns true if the Priority value is Important or Critical; otherwise it returns false. You can use the switch here as a kind of filter for enum ranges.

Bool Methods, Return True and False

Implementation

.NET Framework information

How is the enum switch compiled? The above C# code is compiled into a special .NET Framework instruction called a jump table. The jump table uses the IL instruction switch. It defines one jump "point" to each case. The actual instruction is this: "L_0004: switch (L_001f, L_001f, L_001f, L_0023, L_0023)".

switch Instruction

Summary

The C# programming language

We saw examples of how you can switch on enums in the C# language. Switch can improve performance when it is implemented by a jump table in the MSIL. When you have a set of constants such as the ones shown in this article, I recommend you use switch, as it can have better performance, and the code is clearer to read. An if-statement can always replace a switch.

Intermediate Language If Statement Switch Statement
.NET