I have a few config options in my application along the lines of
const bool ExecuteThis=true;
const bool ExecuteThat=false;
and then code that uses it like
if(ExecuteThis){ DoThis(); }
if(ExecuteThat){ DoThat(); } //unreachable code warning here
The thing is, we may make slightly different releases and not ExecuteThis or ExecuteThat and we want to be able to use consts so that we don't have any speed penalties from such things at run time. But I am tired of seeing warnings about unreachable code. I'm a person that likes to eliminate all of the warnings, but I can't do anything about these. Is there some option I can use to turn just these warnings off?
The quickest way to "Just get rid of it" without modifying your code would be to use
On your Namespace, class or method where you want to supress the warning.
For example, this wont throw the warning anymore:
However be warn that NO METHOD inside this namespace will throw the warning again... and well.. warnings are there for a reason (what if it happened when you did NOT planned it to be unreachable?)
I guess a safer way would be to write the variables in a configuration file, and read them from there at the beginning of the program, that way you don't even need to recompile to have your different versions/releases! Just change the app file and go :D.
about the speed penalty.. yes.. making it this way would inquire in a speed penalty... compared to using
const
but unless you are really worried about wating 1/100 of a millisecond more.. I would go for it that way.Well,
#pragma
, but that is a but grungy. I wonder ifConditionalAttribute
would be better - i.e.Now calls to
DoThis
/DoThat
are only included ifSOME_KEY
orSOME_OTHER_KEY
are defined as symbols in the build ("conditional compilation symbols"). It also means you can switch between them by changing the configuration and defining different symbols in each.The fact that you have the constants declared in code tells me that you are recompiling your code with each release you do, you are not using "contants" sourced from your config file.
So the solution is simple: - set the "constants" (flags) from values stored in your config file - use conditional compilation to control what is compiled, like this:
Then when you recompile you just uncomment the correct #define statement to get the right bit of code compiled. There are one or two other ways to declare your conditional compilation flags, but this just gives you an example and somewhere to start.
The easiest way is to stop writing unreachable code :D #DontDoThat
To disable:
To restore:
For more on
#pragma warning
, see MSDN.Please note that the C# compiler is optimized enough to not emit unreachable code. This is called dead code elimination and it is one of the few optimizations that the C# compiler performs.
And you shouldn't willy-nilly disable the warnings. The warnings are a symptom of a problem. Please see this answer.
What about using preprocessor statements instead?