Home
C#
switch enum Example
Updated Sep 12, 2023
Dot Net Perls
Switch enum. In C# switch can act upon enum values. An enum switch sometimes results in clearer code. The resulting instructions are sometimes faster as well.
A common pattern. The C# switch-enum code pattern is often effective. It is used in many real-world programs (not just website examples).
switch
enum
Example. Enums help us deal with magic constants. For the switch statement here, look at the IsImportant method—it uses 5 explicit cases and a default case.
case
Info IsImportant() has a switch that tests the Priority enum. 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.
return bool
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; } } }
The problem is important. False True
Internals. How is the enum switch compiled? The C# code is compiled into a special .NET instruction called a jump table. The jump table uses the IL instruction switch.
Intermediate Language
L_0004: switch (L_001f, L_001f, L_001f, L_0023, L_0023)
A recommendation. 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
A summary. We saw examples of how you can switch on enums. Switch can improve performance when it is implemented by a jump table in the MSIL. This is determined by the compiler.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 12, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen