Removing code from Release version in .NET.

I've tested some performance benchmarks while using System.Diagnostics.Debug and it seems that all the code associated with the static Debug class is completely removed when the Release config is created. I was wondering how the compiler knows this. Perhaps there is some class or configuration attribute that allows you to precisely specify this behavior.

I am trying to create debug code that I want to completely remove from the Release configuration, and I was wondering if I could do it the same way as the Debug class, where just changing the configuration settings removes the code.

+12


source to share


3 answers


You can apply the ConditionalAttribute with the string "DEBUG" to any method and calls to this element will only be present in DEBUG builds.



This differs from using the #ifdef approach as it allows you to release methods for use by other people in their DEBUG configurations (for example, methods of the Debug class in the .NET platform).

+19


source


Visual Studio defines a DEBUG constant for Debug configuration, and you can use it to port code that you don't want to run in your Release build:

#ifdef DEBUG
  // Your code
#endif

      



However, you can also decorate the method with the Conditional attribute, which means the method will never be called for non-Debug assemblies (the method and any site calls will be removed from the assembly):

[Conditional("DEBUG")]
private void MyDebugMethod()
{
  // Your code
}

      

+16


source


Take a look

+1


source







All Articles