C# Switch EnumUse switch on enum variables. Add cases with enum values, which are constants and can be matched in switch.
can act upon enum values. An enum switch sometimes results in clearer code. It sometimes is faster. This code pattern is often effective. It is used in many real-world programs, not just website examples.SwitchEnum
Enums are useful in your program if it has to use magic constants. For the switch statement, look at the IsImportant method defined at the bottom of this example. It uses 5 explicit cases and a default case.Case
IsImportant: This method contains a switch that tests the parameter of type Priority. It returns true if the Priority value is Important or Critical.True, False
So: You can use the switch here as a kind of filtering mechanism for enum value ranges.Bool Method
C# program that switches on enum
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.
Console.WriteLine("The problem is important.");
// See if Low priority is important.
priority = Priority.Low;
// See if Important priority is.
priority = Priority.Important;
static bool IsImportant(Priority priority)
// Switch on the Priority enum.
The problem is important.
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.IL: switch
Switch instruction: IL
L_0004: switch (L_001f, L_001f, L_001f, L_0023, L_0023)
When you have a set of constants, I recommend you use switch—it can have better performance. And the code is clearer to read. If necessary, an if-statement can always replace a switch.If
Summary. 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. This is determined by the compiler.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.