简体   繁体   中英

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;
        }
    }
}

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 
}

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.

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.

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.

不,默认情况不是必需的。

From a purely code perspective, there's no requirement to have a default case. It's solely a matter of your logical requirements.

如果你将枚举值添加到enum中,则需要使用枚举未定义的值(不会抛出异常)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM