Is there a warning (error) similar to C4061 for C #

Usually, if I use the switch for enumerations in C #, I should write something like this:

switch (e) { case E.Value1: //... break; case E.Value2: //... break; //... default: throw new NotImplementedException("..."); } 

In C ++ (for VS), I can enable the C4061 and C4062 warnings for this switch, make their errors and check the compilation time. In C #, I need to move this check at runtime ...

Does anyone know how in C # I can check this at compile time? Maybe there is a warning, disabled by default, which I missed, or in some other way?

+7
source share
1 answer

No, there is no compile time check - it is legal to have a / case switch that only processes some of the named values. You could turn it on, but there are some problems.

First, it is fully valid (unfortunately) for an enumeration value that does not have any "named" values:

 enum Foo { Bar = 0, Baz = 1 } ... Foo nastyValue = (Foo) 50; 

Given that any value is possible in the switch / case, the compiler may not know that you did not want to try to handle the unnamed value.

Secondly, this will not work with Flags enums - the compiler really does not know what values โ€‹โ€‹are intended for convenient combinations. That might have concluded, but that would have been a bit unpleasant.

Thirdly, this is not always what you want - sometimes you really only want to answer a few cases. I would not like to suppress warnings on a fairly regular basis.

You can use Enum.IsDefined to test this, but it is relatively inefficient.

I agree that all this is a little painful - enums are a bit of a nasty area when it comes to .NET :(

+5
source

All Articles