Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defines.Debug vs #if DEBUG

Tags:

c#

I've started to use a define class like so:

internal sealed class Defines
{
    /// <summary>
    /// This constant is set to true iff the define DEBUG is set.
    /// </summary>
    public const bool Debug =
  #if DEBUG
   true;
  #else
   false;
  #endif
}

The advantages I see is:

  1. Ensures I don't break stuff that with an #if..#else..#endif would not be checked by compiler.
  2. I can do a find references to see where it is used.
  3. It's often useful to have a bool for debug, defines code is longer/more messy.

Possible disadvantage I see:

Compiler can't optimize unused code if the Defines class is in another assembly. Which is why I have made internal.

Am I missing any other disadvantages?

[Edit] Typical examples of usage:

private readonly Permissions _permissions = Defines.Debug ? Permissions.NewAllTrue()
                                                          : Permissions.NewAllFalse();

Or:

var str = string.Format(Defines.Debug ? "{0} {1} ({2})" : "{0} {1}", actual, text, advance);
like image 915
weston Avatar asked Dec 15 '11 10:12

weston


People also ask

What is the meaning of debug in VS code?

A Debug value indicates a debug configuration. When you start the app (press the green arrow or F5) in a debug configuration, you start the app in debug mode, which means you are running your app with a debugger attached.

What is the difference between debug and Release?

By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled. As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

What is visual debug?

Visual debugging provides the Visual Debug view for you to interact with your COBOL or PL/I debug session. With this view, you can visualize the stack trace, set breakpoints, and run to a selected call path.


1 Answers

I see at least one big disadvantage: if Debug is false, this code will cause a warning:

if (Debug)
    Console.WriteLine("Debug");

Because the compiler will detect that the condition is never met, so the Console.WriteLine call is unreachable.

like image 191
Thomas Levesque Avatar answered Sep 18 '22 15:09

Thomas Levesque