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?
In C# you can do
#if DEBUG
//debug-mode only snippet go here.
#endif
Here's the reference documentation for the #if
directive.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With