tags:

views:

194

answers:

3

I've been doing some performance testing around the use of System.Diagnostics.Debug, and it seems that all code related to the static class Debug gets completely removed when the Release configuration is built. I was wondering how the compiler knows that. Maybe there is some class or configuration attribute that allows to specify exactly that behavior.

I am trying to create some debugging code that I want completely removed from the Release configuration, and I was wondering if I could do it just like the Debug class where simply changing the configuration parameters removes the code.

+14  A: 

You can apply the ConditionalAttribute attribute, with the string "DEBUG" to any method and calls to that item will only be present in DEBUG builds.

This differs from using the #ifdef approach as this allows you to release methods for use by other people in their DEBUG configurations (like the Debug class methods in the .NET framework).

Jeff Yates
Didn't know that, that could come in useful!
Stormenet
This is exactly what I was hoping for, since it is customizable and extensible.
Curro
+1  A: 

Have a look at preprocessor directives...

#if DEBUG
    //code
#endif
ZombieSheep
+8  A: 

Visual Studio defines a DEBUG constant for the Debug configuration and you can use this to wrap the code that you don't want executing in your Release build:

#ifdef DEBUG
  // Your code
#endif

However, you can also decorate a method with a Conditional attribute, meaning that the method will never be called for non-Debug builds (the method and any call-sites will be removed from the assembly):

[Conditional("DEBUG")]
private void MyDebugMethod()
{
  // Your code
}
Dave R.
Conditional methods can never return anything other than void...
Pop Catalin
Thanks for the edit Pop - I missed that in my haste!
Dave R.