Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing code from Release build in .NET

Tags:

c#

debugging

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.

like image 960
Curro Avatar asked Dec 03 '08 15:12

Curro


3 Answers

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).

like image 167
Jeff Yates Avatar answered Oct 22 '22 19:10

Jeff Yates


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
}
like image 35
Dave R. Avatar answered Oct 22 '22 20:10

Dave R.


Have a look at preprocessor directives...

#if DEBUG
    //code
#endif
like image 36
ZombieSheep Avatar answered Oct 22 '22 20:10

ZombieSheep