Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make compilation different between Debug against Release?

I'm a newbee to C#, and encounter a problem when compiling a C# project. It's about debug log in Debug and Release modes. I want the log function to be called in Debug mode, but not called in Release mode, taking performance into account. I know in C/C++, this is easy to be done:

// this is C/C++ sample, not C#
#ifdef DEBUG
#define DebugLog(CString,__VA_ARGS__) LogFunction(CString,__VA_ARGS__)
#else
#define DebugLog
#endif

In the above C/C++ code, the DebugLog() is compiled and called in Debug mode, but not compiled or called in Release mode, so the performance can be ensured.

Is there anyway in C# that works like the above C/C++ codes?

like image 262
McArthor Lee Avatar asked Apr 26 '11 04:04

McArthor Lee


2 Answers

In C# you can do

#if DEBUG
                //debug-mode only snippet go here.
#endif

Here's the reference documentation for the #if directive.

like image 185
Bala R Avatar answered Oct 23 '22 23:10

Bala R


The equivalent is the [Conditional] attribute on a method. Like this:

[Conditional("DEBUG")]
public static void DebugLog(string fmt, params object[] args) {
    // etc..
}

In the Release build (with DEBUG not defined), both the method and the calls to the method are removed by the compiler. Before you re-invent this wheel, be sure to review the Debug and Trace classes in the .NET framework, they already do this. And have lots of flexibility to redirect the debug/trace info.

like image 44
Hans Passant Avatar answered Oct 23 '22 21:10

Hans Passant