Is there a way to get the C# compiler to emit an error if a switch(enum_val) is missing a case statement?

前端 未结 8 1883
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 04:27

I just realized I added a value to the list of \"must-handle\" values in my enum, but I didn\'t catch it until runtime. I know the C# compiler is really powerful when it com

8条回答
  •  庸人自扰
    2020-12-06 05:11

    You could throw an exception early on if the enum size, hopefully alerting you very early on when a change to the enum has been made:

    enum MyEnum {A, B};
    
    class TestEnum
    {
        // Static constructor
        static TestEnum()
        {
            // Check if this code needs updating as the enum has changed
            if (Enum.GetNames(typeof(MyEnum)).Length != 2)
            {
                // If this fails update myFunction and the number above
                throw new Exception("Internal error - code inconsistency");
            }
        }
    
        // My function that switches on the enum
        string myFunction(MyEnum myEnum)
        {
            switch (myEnum)
            {
                case MyEnum.A: return "A";
                case MyEnum.B: return "B";
            }
            throw new Exception("Internal error - missing case");
        }
    }
    

    This will throw an exception from the static constructor if the number of items in the enum is changed. So the developer knows he needs to update the code. You could even do this check from a unit test that you run with your build.

提交回复
热议问题