TL;DR: In C# use [DebuggerDisplay(“”)] on your classes and follow better practices.

So lets say we have a class (C#) that looks like this:

public class Person { public string Name { get; set; } }

What will Visual Studio’s debugger show me for this guy?



Not very awesome at all. And anything less than awesome, is just no bueno.

We can make this a lot better. All the debugger is doing is calling the ‘ToString’ function on your object which by default is just returning the type name. If you see the {} around the value in the debugger you know that it is calling the ‘ToString’ method. So the first thing we could do is just override the ‘ToString’ method.

public class Person { public string Name { get; set; } public override string ToString(){ return Name; } }

Which gives us:



So we can see that the {} are still there, but now we have the Name property being displayed for our class which can make rapid debugging SO much easier. So this is great and all, but as a web guy I often use the ‘ToString’ function to make my life easier and want to use it for ‘not-debugger’ stuff. So what am I going to do? Suffer? Hell no. Enter the DebuggerDisplayAttribute. Lets change our code to use it.

[DebuggerDisplay("{Name}")] public class Person { public string Name { get; set; } }

This gives us:



Bam! Much better. So in the [DebuggerDisplay] attribute all you have to do is follow a convention similar to string.Format. In between {} just put the code you want to evaluate. Yes, you can even use methods. [DebuggerDisplay(“{MyMethod()}”)] But don’t think that there isn’t a way to shoot your self in the foot with these (Don’t call methods that change state, or you will find yourself in very nasty place).

So, there you go. I simple way to enhance your code for you and your friends. Its a simple thing to add, but doing so can make life so much easier when you are 16 levels deep and trying to keep track of what the hell is going on.

Enjoy.

Better Practices in DebuggerDisplay

MSDN