Two handy attributes for use when debugging

I have heard that some people need to step through their code in order to find something called “a bug” – a mistake in the coding. Can you imagine? Anyway, just in case you find yourself having to perform such an unsavoury chore (for a friend, no doubt), then I suggest you look at the two following attributes that can be added to classes, methods, properties, etc.

First is the DebuggerStepThrough attribute. Decorate your code with this attribute to prevent the debugger from stepping into the code:

public int Foo(x)
     var y = x * 2;
     Console.WriteLine("2 times {0} is {1}", x, y);

If you are stepping though your program and a call to Foo() is made, the debugger will simply jump over the call to Foo(); the output of Foo() will appear on the console, but the normal 4 step points through the code will not occur.

Secondly, you can change the value displayed in the locals and watch windows (and all other places where the debugger shows an item’s value) by using the DebuggerDisplay attribute:

[DebuggerDisplay("Bar {Name()}: {Size()} bytes")]
public class Bar
     public string Name { get; set; }
     public int Size { get { return Name.Length; } }
     public double Amount { get; set; }
     var X = new Bar() { Name="Fred", Amount=20 };

Now, when you look at X, instead of seeing "{Bar}" under the value column of the debugger display, you will see "Bar Fred: 4 bytes"
(Caveat: make sure you read this MSDN section before you go hog-wild with DebuggerDisplay – if misused, it can a be hog on your CPU and even cause program crashes.)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s