views:

187

answers:

4

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?

+5  A: 

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)

Binary Worrier
That's a good point. But in my situation, I don't think it applies (it would lead to almost empty classes, containing some logic that's not of their responsibility. Typically, I have some DataContracts containing enumerated member, and my GUI switches on those members to see how to format them.)
Brann
A good pattern, but use it with care. If your enum is large and your switch only needs to handle a few cases you probably don't want to create a zillion classes.
0xA3
+1 for the edit. =)
J. Steen
+1 for the edit too :)
Brann
A: 

It's quite common to have

case myEnum.Success
  //OK; Do nothing
  break;

Therefore, no warning.

GSerg
I don't understand your answer. I do want to have warnings :)
Brann
A: 

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.

Jon Skeet
+1  A: 

Never used it, but FxCop may be helpful. It supports writing custom rules. Of course, that's not a compile-time check, but something that can be integrated into your processes.

Dmitry Ornatsky