0

I am adding debug statements in a few places in my code. Each time I use a boolean to know if I should be debugging. This boolean is a property that checks a few unerlying conditions. To avoid unecessary boolean checks in the actual release build, I am also adding a compilation symbol.

#if MY_DEBUG
            if (IsDebugging) {
               ...
            }
#endif

Is there are way to somehow merge both if on one line without needing the #endif at the end? Something that would look somewhat like this:

#if MY_DEBUG if (IsDebugging) {
               ...
            }

EDIT: Thank you @canton7 I didn't know about the ConditionalAttribute [Conditional("MY_DEBUG")]

I think this is what I was looking for

Dypsloom
  • 1
  • 1
  • No, you cannot. – Dai Mar 22 '22 at 11:18
  • If you're doing this a lot, that's a bit of a red flag for me anyway. Debug code should be as close to release code as possible. – DavidG Mar 22 '22 at 11:20
  • "Each time I use a boolean to know if I should be debugging." - [just use `Debugger.IsAttached`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.isattached?view=net-6.0) – Dai Mar 22 '22 at 11:20
  • Note that you can also put [`[Conditional("MY_DEBUG")]`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=net-6.0) on a suitable *method*, and then call that method lots. The entire method and all of the calls to it will be removed if `MY_DEBUG` isn't set. This is what [`Debug.WriteLine`](https://source.dot.net/#System.Private.CoreLib/Debug.cs,133) does for instance -- all calls to `Debug.WriteLine` are simply compiled out if `DEBUG` isn't set – canton7 Mar 22 '22 at 11:23
  • 2
    "To avoid unecessary boolean checks in the actual release build" Really? *That's* your bottleneck? – Sweeper Mar 22 '22 at 11:24

0 Answers0