Reputation: 57179
I'm aware that you can use #if DEBUG
and the likes in C#, but is it possible to create a method, or class, that is ignored completely, including all usages that are not wrapped inside an #if DEBUG
block?
Something like:
[DebugOnlyAttribute]
public void PushDebugInfo()
{
// do something
Console.WriteLine("world");
}
and then:
void Main()
{
Console.WriteLine("hello ");
Xxx.PushDebugInfo();
}
which, if DEBUG
is defined will print "hello world", otherwise just "hello ". But more importantly, the MSIL should not contain the method-call at all in release builds.
I believe the behavior I'm after is something similar to Debug.WriteLine, whose call is completely removed and has no impact on performance or stack depth in release builds.
And, if possible in C#, would any .NET language using this method behave the same (i.e., compile-time vs run-time optimization).
Also tagged f#, because essentially I will need this method there.
Upvotes: 1
Views: 857
Reputation: 64943
It seems like you're looking for ConditionalAttribute
.
For example, this is a portion of Debug
class source code:
static partial class Debug
{
private static readonly object s_ForLock = new Object();
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition)
{
Assert(condition, string.Empty, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition, string message)
{
Assert(condition, message, string.Empty);
}
................................
Upvotes: 7
Reputation: 3589
I've seen the following method used in some places, although it might not be the best way.
public static class Debug
{
public static bool IsInDebugMode { get; set; }
public static void Print(string message)
{
if (IsInDebugMode) Console.Write(message);
}
}
You can then set the IsInDebugMode
boolean somewhere in your main method and do Debug.Print("yolo")
calls all over.
EDIT: This can of course be expanded on with additional wrappers for formatted output, with automatic newline and so on.
Upvotes: 1
Reputation: 62498
You can decorate your method with [Conditional("DEBUG")]
so that it is only executed in debug mode and will not be executed in Release mode.
You can read more about the Conditional attribute on MSDN which says:
The Conditional attribute is often used with the
DEBUG
identifier to enable trace and logging features for debug builds but not in release builds
Upvotes: 1