Search code examples
c#warningssuppress-warningscompiler-directives

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


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?


Solution

  • 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