Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if DEBUG and return statements - Unreachable code warning

I am facing this little piece of code:

#if DEBUG
return thisVariable;
#endif
return thatVariable; //<-- warning CS0162 here

It works fine, except I am getting a warning on the second return statement that the code is unreachable. Despite the warning, the code is actually very reachable when running the program in release mode.

Why am I getting this warning?

like image 783
Richnau Avatar asked Feb 12 '16 13:02

Richnau


1 Answers

If you are performing a build where the DEBUG symbol is defined, then the compiler is performing its static analysis of your code assuming that first return is in effect and not excluded. So your code would be seen as:

return thisVariable;
return thatVariable;

In that context it is clear the second return statement won't be reached in such a build. When you switch to a build configuration where DEBUG is not defined, then you should not see the warning.

Consider using #else (docs) to avoid the second return statement when DEBUG is defined.

There's also this relevant tidbit from here:

Although the compiler does not have a separate preprocessor, the directives described in this [C# Preprocessor Directives] section are processed as if there were one.

In other words, the C# compiler's static analysis is not aware of the preprocessor directives; they have been processed at that point already and the static analysis only sees the code that resulted from the preprocessing phase.

like image 134
Chris W. Rea Avatar answered Nov 15 '22 21:11

Chris W. Rea