[c#] "Debug only" code that should run only when "turned on"

I would like to add some C# "debug only" code that only runs if the person debugging requests it. In C++, I used to do something similar to the following:

void foo()
{   
  // ...
  #ifdef DEBUG
  static bool s_bDoDebugOnlyCode = false;
  if (s_bDoDebugOnlyCode)
  {
      // Debug only code here gets executed when the person debugging 
      // manually sets the bool above to true.  It then stays for the rest
      // of the session until they set it to false.
  }
  #endif
 // ...
}

I can't do exactly the same in C# since there is no local statics.

Question: What is the best way to accomplish this in C#?

  1. Should I use a private class static field with C# preprocessor directives (#if/#endif DEBUG)?
  2. Should I use the Conditional attribute (to hold the code), and then a private class static field (not surrounded by C# preprocessor directives #if/#endif DEBUG?).
  3. Something else?

This question is related to c# debugging preprocessor

The answer is


If you want to know whether if debugging, everywhere in program. Use this.

Declare global variable.

bool isDebug=false;

Create function for checking debug mode

[ConditionalAttribute("DEBUG")]
    public static void isDebugging()
    {
        isDebug = true;
    }

In the initialize method call the function

isDebugging();

Now in the entire program. You can check for debugging and do the operations. Hope this Helps!


I think it may be worth mentioning that [ConditionalAttribute] is in the System.Diagnostics; namespace. I stumbled a bit when I got:

Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)

after using it for the first time (I thought it would have been in System).


What you're looking for is

[ConditionalAttribute("DEBUG")]

attribute.

If you for instance write a method like :

[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
    Console.WriteLine("This message was brought to you by your debugger : ");
    Console.WriteLine(message);
}

any call you make to this method inside your own code will only be executed in debug mode. If you build your project in release mode, even call to the "MyLovelyDebugInfoMethod" will be ignored and dumped out of your binary.

Oh and one more thing if you're trying to determine whether or not your code is currently being debugged at the execution moment, it is also possible to check if the current process is hooked by a JIT. But this is all together another case. Post a comment if this is what you2re trying to do.


You could try this if you only need the code to run when you have a debugger attached to the process.

if (Debugger.IsAttached)
{
     // do some stuff here
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to debugging

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug

Examples related to preprocessor

#ifdef replacement in the Swift language How to determine whether code is running in DEBUG / RELEASE build? How to convert an enum type variable to a string? "Debug only" code that should run only when "turned on" Can gcc output C code after preprocessing? #if DEBUG vs. Conditional("DEBUG") #define in Java What is the worst real-world macros/pre-processor abuse you've ever come across?