Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# is default case necessary on a switch on an enum?

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;         }     } } 
like image 731
mirezus Avatar asked Dec 17 '10 16:12

mirezus


People also ask

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

What is '~' in C programming?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What is operators in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.


1 Answers

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  } 
like image 110
JaredPar Avatar answered Sep 22 '22 13:09

JaredPar