Should I throw NotImplementedException() on default: if I have cases for all possible enum types?
It really depends on the specific process, but yes, it's good process to respond in the default: case if something wasn't supposed to be there.
That sounds like a reasonable option.
Personally, I would create a new type of exception (perhaps an InvalidEnumException
or give it another name that will make sense to the support team) and throw that.
I'd throw ApplicationException
because if your code reaches default and you didn't expected it this means that something in your code is not behaving as you where thinking.
I'd say at least you should put a Debug.Fail()
there.
You should throw an exception in case if the method in no way can proceed. But if you are like converting your enum values to string representations, then you can just return some warning string instead. The product will not crash on users due to an obvious mistake, there will be probably a workaround, and everyone will be happy.
Maybe not NotImplementedException, but ArgumentException. It would really depend on where you're using it.
It really depends on your use case. It will be helpful if you throw an exception during the early days of integration. The users of your library can immediately come to know the errors
You should first consider what it would mean if you got a value outside of the known cases- what does the variable being switched on represent? Then you might simply use an exception type that fits what is actually happening.
If I remember correctly default part is optional. In case of switching on enum it imposable to be in default branch if You
have cases for all possible enum types.
How can it be? I can't imagine...
So simply write switch statement without default part.
If you're looking for a value that must, by definition, correspond to the value of an enumeration, and you've received something else, that's definitely an invalid argument.
But now you have to consider the context.
Is the method private, and only accessible by members of your class library or application? If it is, it's a coding error that shouldn't EVER occur in the first place. Assert and fail.
If, on the other hand, it's a public or protected method, and can be accessed by clients consuming your library, you should definitely throw with a meaningful message (and preferably a well-known exception type).
It's important to remember that enumerations are not range-checked in the Framework. I may specify that a method requires a parameter of type Environment.SpecialFolder; but it will accept any 32-bit integer value.
So, in short, if your method is for public consumption, yes, by all means, throw. If it's not for public consumption, Assert.