tags:

views:

131

answers:

4

I'm having trouble the same instance of a C# class being used in multiple places. I'd like to be able to tell at a glance in the debugger which instance is which, so I've added a field called DebugUID like so:

public readonly string DebugUID = Guid.NewGuid().ToString();

and I've also added the attribute [DebuggerDisplay("DebugUID= {DebugUID}")] to the class.

I'd like the compiler to ignore the DebugUID field in release mode. If it were a method, I'd add [Conditional("Debug")] before it, but it won't let me do that for fields. How do make a field be debug-only in C#?

+12  A: 

C# has conditional compilation features analagous to those of C/C++. You can use the #if statement with a compilation directive like DEBUG to accomplish this.

#if DEBUG
public readonly string DebugUID = Guid.NewGuid().ToString();
#endif

Since by default only "Debug" configurations define the DEBUG directive, this will only compile in Debug mode. In Release mode the code inside the #if will be ignored.

Adam Robinson
+1  A: 

Try using the "preprocessor" directive #if:

class Value {

#if DEBUG
private readonly string DebugUID = Guid.NewGuid().ToString()
#endif

}

You will have to make sure, though, that the DEBUG flag is set for debugging builds (and of course, unset for release builds).

Dirk
+1  A: 

You could use a conditional preprocessor include

#if DEBUG
private readonly string debugId = Guid.NewGuid().ToString();
#endif
Charles Bretana
+4  A: 

Can I suggest an alternative that involves using the debugger rather than writing code?

Right-click the instance in the watch window and choose "Assign Object ID". That object will now appear with that ID throughout your debug session. Repeat for other instances of the same class that are of interest to you.

HTH, Kent

Kent Boogaart
I don't think I can do that in this case, at least not at first - there are too many of the objects in question - but thanks for letting me know about that feature!
Simon