Is there a way to get VS2008 to stop warning me about unreachable code?

Earlz picture Earlz · Dec 18, 2009 · Viewed 9.1k times · Source

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?

Answer

jason picture jason · Dec 18, 2009

To disable:

#pragma warning disable 0162

To restore:

#pragma warning restore 0162

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.