How do I use an If DEBUG statement in C# without the IDE thinking code is unreachable?

1.7k views Asked by At

I've got some code that needs to work slightly differently in debug and release modes. It has a constant called PrettyPrint that is set to true in some modes and false in others, and I sometimes change those around.

#if DEBUG
        public const bool PrettyPrint = true;
#else
        public const bool PrettyPrint = false;
#endif

// ...snip...
string start, end, comma, innerIndentation;
if (Printer.PrettyPrint) {
    innerIndentation = indentation + "  ";
    start = "[\n";
    end = indentation + "]";
    comma = ",\n" + innerIndentation;
} else {
    innerIndentation = "";
    start = "[";
    end = "]";
    comma = ",";
}
// Then do some prints using the initialized strings as constants

This works great, and the compiler is smart enough to optimize the if away. However, I get an annoying warning:

warning CS0162: Unreachable code detected

Is there a way to avoid this warning without doing any of the following:

  • using #if directly in the code - as it makes that part of the code quite ugly and I'd like to avoid #ifs as much as possible.
  • suppressing CS0162 for other cases - as I find that warning invaluable in finding broken code.

How do I use an #if DEBUG statement without the IDE believing that all code that follows is unreachable?

5

There are 5 answers

1
BinaryTox1n On BEST ANSWER

You could try:

innerIndentation = Printer.PrettyPrint ? indentation + " " : "";

start = Printer.PrettyPrint ? "[\n" : "[";

end = Printer.PrettyPrint ? indentation + "]" : "]";

comma = Printer.PrettyPrint ? ",\n" + innerIndentation : ",";

But if it were me, I would just use an #if #else

0
OilyHamster On

You could do the following to get round it.

Printer.PrettyPrint.Equals(true)
0
SLaks On

You could change PrettyPrint to a normal field instead of const.
You'll lose the compiler optimization, but that shouldn't matter.

I'm pretty sure you could also make it readonly without getting the warning; try it.

0
Femaref On

While I currently don't have an idea how to work it into your code, you might find the ConditionalAttribute helpful. You'd get around using preprocessor directives, but you might have to rework your code.

0
Richard Schneider On

Change the PrettyPrint from a const to a field.

#if DEBUG          
    public bool PrettyPrint = true;  
#else 
    public bool PrettyPrint = false;  
#endif