Reputation: 317
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?
Upvotes: 16
Views: 17138
Reputation: 108957
In C# you can do
#if DEBUG
//debug-mode only snippet go here.
#endif
Here's the reference documentation for the #if
directive.
Upvotes: 20
Reputation: 133
Other methodology, can include a "Conditional" attribute like
[Conditional("DEBUG")]
void DebugLog()
{
// method code here
}
More informations can be found here in MSDN
Upvotes: 1
Reputation: 1
/// <summary>Function to Set Debug Flag to true if DEBUG is in Effect</summary>
/// <param name="theDebugFlag">output - true if DEBUG, unchanged if RELEASE</param>
[Conditional("DEBUG")]
static void QueryDebugStatus(ref Boolean theDebugFlag)
{
theDebugFlag = true;
}
Upvotes: 0
Reputation: 941455
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.
Upvotes: 16
Reputation: 88355
You can do the same thing in C#. In the project properties, you can set a conditional compilation symbol like DEBUG
. In fact, I think Visual Studio will do this by default when you create a project - it will add a DEBUG
flag when the project is in Debug mode, and remove the flag when you switch to Release mode. This can be configured in the Project Properties->Build tab. You can also add your own flags for things like platform-specific code. The Pocket_PC
flag was a famous one for doing old-school Windows Mobile development on the .NET Compact Framework.
With this, you can add the pre-processor directives like this:
#if DEBUG
// debug code here
#endif
Upvotes: 4