How to run some code based on release or debug build mode?

849 Views Asked by At

I have a variable(i.e bool releaseMode = false;) I want the value of the variable to be set based on whether we are in release mode(releaseMode = true;) else debug mode(releaseMode = false;)

1

There are 1 best solutions below

2
On BEST ANSWER

From your question, you can use that:

/// <summary>
/// Indicate if the executable has been generated in debug mode.
/// </summary>
static public bool IsDebugExecutable
{
  get
  {
    bool isDebug = false;
    CheckDebugExecutable(ref isDebug);
    return isDebug;
  }
}

[Conditional("DEBUG")]
static private void CheckDebugExecutable(ref bool isDebug)
  => isDebug = true;

Of course you can swap name to:

IsReleaseExecutable

return !isDebug;

This approach implies that all code is compiled. Thus any code can be executed depending on this flag as well as any other behavior parameter concerning the user or the program, such as for example the activation or the deactivation of a debugging and tracing engine. For example:

if ( IsDebugExecutable || UserWantDebug )  DoThat();

Else a preprocessor directive like this:

C# if/then directives for debug vs release

#if DEBUG vs. Conditional("DEBUG")