In C# is default case necessary on a switch on an enum?
Solution 1
It's a common misconception that .Net enum values are limited to the ones declared in the Enum. In reality though they can be any value in the range of the base type of the enum (int
by default). For example the following is perfectly legal
MyMethod((MyEnum)42);
This code will compile without warnings and hit none of your case
labels.
Now whether your code chooses to handle this type of scenario is a policy decision. It's not necessary but I'd certainly recomend having one. I prefer to add a default
to every switch
on enum I write specifically for this scenario with the following pattern
switch (value) {
...
default:
Debug.Fail(String.Format("Illegal enum value {0}", value));
FailFast(); // Evil value, fail quickly
}
Solution 2
It's not strictly necessary, but someone may pass in a value not covered by your enum (since enumerations do not actually restrict the range of permissible parameter values).
I typically add a default and throw
if the specified value is unexpected.
Solution 3
It is not technically necessary, but because you can easily cast a value of MyEnum
s underlying type (usually int) to an instance of MyEnum
. Hence it is good practice to add a default statement with a Debug.Assert()
in it.
Solution 4
It is not required but good practise as someone might introduce a new enumeration later on. For example throw an exception that indicates that 'unknown' enumeration is not handled.
Solution 5
No, the default case is not required.
mirezus
Updated on June 03, 2022Comments
-
mirezus almost 2 years
I've seen posts relating to C++, but am asking specifically for C# .NET (4.0+).
In the following example is a default case necessary?
public enum MyEnum : int { First, Second } public class MyClass { public void MyMethod(MyEnum myEnum) { switch (myEnum) { case MyEnum.First: /* ... */ break; case MyEnum.Second: /* ... */ break; default: /* IS THIS NECESSARY??? */ break; } } }
-
Eric Lippert over 13 yearsI would add to Jared's answer that if you have an enum based on a byte, and you have all 256 cases in your switch, even then the compiler still might want a default case for definite assignment checking purposes. See blogs.msdn.com/b/ericlippert/archive/2009/08/13/… for details.
-
ChaseMedallion about 7 yearsAnother case where this comes into play is if the enum is defined in a different assembly. In that case, someone might add a field to the enum and then run your code against the new version without recompiling. The compiler insists on generating code that is robust to this kind of thing.