Why do “Not all code paths return a value” with a switch statement and an enum?

前端 未结 5 1942
天涯浪人
天涯浪人 2020-12-17 08:28

I have the following code:

public int Method(MyEnum myEnum)
{
    switch (myEnum)
    {
        case MyEnum.Value1: return 1;
        case MyEnum.Val         


        
5条回答
  •  一个人的身影
    2020-12-17 09:18

    If you change the values in your enum (adding a fourth) your code will break. You should add a default: case to your switch statement.

    of course, the other way to achieve this would be to define the integer values in your enum...

    public enum MyEnum
    {
        Value1 = 1,
        Value2 = 2,
        Value3 = 3
    }
    

    and then cast your enum as an int in code. Instead of int myInt = Method(myEnumValue); you can use int myInt = (int)myEnum

提交回复
热议问题