Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have the c# compiler display warnings when a switch statement do have unhandled cases?

Consider the following code :

        private enum myEnum
        {
            A,
            B
        }
        private void myMethod(myEnum m)
        {
            switch (m)
            {
                case myEnum.A:
                    //do stuff
                break;
                case myEnum.B:
                   //do stuff
                break;
                default:
                   throw new NotImplementedException(m.ToString());
            }
        }

If I ever add a third member C to myEnum, I will only be warned at runtime by a NotImplementedException

What I'd like to do is have the compiler warn me when there's a switch with unhandled cases and no default: case.

Is there a way to do that, or other solution to this problem, the ultimate goal being to be warned at compile-time that something is missing?

like image 331
Brann Avatar asked Apr 02 '09 08:04

Brann


2 Answers

Unfortunately here is no compiler feature to do this for you.

Instead of having an enum, have a base class or an interface. MyMethod is defined on the interface.

Each each enum member now becomes a class with different behaviour for myMethod. If you add a class (to extend the options, currently you'd add an enum item)but don't implement myMethod, you'll get a compiler error.

having lots of place's in code where you provide different behaviour in select statements is a smell that you may need to use polymorphism.

EDIT

The best advice I can give is to build unit tests for each function that relies on the switch statement, and call it for each value in the enumeration (you can get the values at runtime with the GetValues member on the Enum class)

like image 177
Binary Worrier Avatar answered Sep 29 '22 15:09

Binary Worrier


No, there's nothing in the language to check this.

You can have a:

default:
    throw new ArgumentOutOfRangeException("Invalid value or bug");

case, but obviously that's execution-time rather than compile-time.

like image 31
Jon Skeet Avatar answered Sep 29 '22 15:09

Jon Skeet