Sunday, November 18, 2007

Another small yet useful thing. Usually when we have an object of a class and want it to be more debugger friendly, we override the ToString method. From that method, we return something meaningful, like the name of a client.

It comes out, that there is a far better way to do it, than to override the ToString method. Introduced in .NET 2.0, there is a DebuggerDisplayAttribute class. It's an attribute, so we apply it as any other class-level attribute by decorating our class. What is more interesting is the fact, that we can apply it to a field or property!

Inside the attribute definition, we have a way to format the final string a bit. We can put variables that will be replaced by a field or property value or even by a method call! Now that's interesting.

Given the following  code:

[DebuggerDisplay("Name: {name}")]
class Client
{
    public Client(string name)
    {
        this.name = name;
    }
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    [DebuggerDisplay("HashCode: {GetHashCode()}")]
    public string HashCode
    {
        get { return GetHashCode().ToString(); }
    }
}

We get something like this inside debugger:

Told you. A nice little feature!

Sunday, November 18, 2007 12:46:41 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
Wednesday, November 28, 2007 3:59:16 PM (Central European Standard Time, UTC+01:00)
Always a handy tip, I only worked this out recently too, thanks to Imar Spanjaars!
Shannon
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview