Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

COTW: DebuggerDisplayAttribute Class

leave a comment »

The DebuggerDisplayAttribute[^] class allows you to specify how your classes will be displayed in a debugger. Specifically, you can define a string format that uses properties or fields from your class. This string will then be used by the debugger when it displays debug information about your class (e.g. in the Watch windows of Visual Studio).

MSDN[^] has a good write up on how to use this attribute. In the class below I have specified a string format that includes the Name property:

[DebuggerDisplay("The name of MyClass is {Name}")]
public class MyClass {
    /// <summary>
    /// Initializes a new instance of the
    /// <see cref="MyClass"/> class.
    /// </summary>
    /// <param name="name">The name.</param>
    public MyClass(String name) {
        this.name = name;
    }
 
    /// <summary>
    /// Holds the name.
    /// </summary>
    private String name;
 
    /// <summary>
    /// Gets or sets the name.
    /// </summary>
    /// <value>The name.</value>
    public String Name {
        get {
            return this.name;
        }
        set {
            this.name = value;
        }
    }
}

Assuming that I create a new instance of MyClass and pass the string “Test1” into the constructor, then Visual Studio will display this object like this:

DebuggerDisplayAttribute (1)

If you find that you often drill down in the Watch window to view a few properties of your classes, then you may want to use this attribute. If you are designing reusable classes or components, then you should definitely consider using this attribute. For further reading on this subject, this article[^] is a great resource.

Advertisements

Written by Tom

October 16, 2007 at 8:11 am

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: