Creating Custom Debugging Displays for Your Classes

Creating Custom Debugging Displays for Your Classes


You have a set of classes that are used in your application. You would like to see at a glance in the debugger what a particular instance of the class holds. The default debugger display doesn't show any useful information for your class today.


Add a DebuggerDisplayAttribute to your class to make the debugger show you something you consider useful about your class. For example, if you had a Citizen class that held the honorific and name information, you could add a DebuggerDisplayAttribute like this one:

	[DebuggerDisplay("Citizen Full Name = {_honorific}{_first}{_middle}{_last}")]
	public class Citizen
	    private string _honorific;
	    private string _first;
	    private string _middle;
	    private string _last;

	    public Citizen(string honorific, string first, string middle, string last)
	        _honorific = honorific;
	        _first = first;
	        _middle = middle;
	        _last = last;

Now when instances of the Citizen class are instantiated, the debugger will show the information the way the DebuggerDisplayAttribute on the class directs it to. To see this, instantiate two Citizens, Mrs. Alice G. Jones and Mr. Robert Frederick Jones like this:

	Citizen mrsJones = new Citizen("Mrs.","Alice","G.","Jones");
	Citizen mrJones = new Citizen("Mr.", "Robert", "Frederick", "Jones");

When this code is run under the debugger, the custom display is used, as shown in Figure.

Debugger display controlled by DebuggerDisplayAttribute


It is nice to be able to see the pertinent information for classes you write quickly. But the more powerful part of this feature is the ability for your team members to quickly understand what this class instance holds. The this pointer is accessible from the DebuggerDisplayAttribute declaration, but any properties accessed using the this pointer will not evaluate the property attributes before processing. Essentially, if you access a property on the current object instance as part of constructing the display string, if that property has attributes, they will not be processed, and therefore you may not get the value you thought you would. If you have custom ToString( ) overrides in place already, the debugger will use these as the DebuggerDisplayAttribute without your specifying it, provided the correct option is enabled under Tools\ Options\Debugging as shown in Figure.

See Also

See the "Using DebuggerDisplayAttribute" and "DebuggerDisplayAttribute" topics in the MSDN documentation.

Setting the debugger to call ToString( ) for object display

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows