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]  | 
 Tuesday, November 06, 2007

Some time ago I've written an article on creating memory efficient events. Over a year later - that is today, I have found that a Control class has a built in property Events that is there for this very purpose!

Ehh. ASP.NET never stops to surprise me (both positively and negatively). This time it was positive.

Tuesday, November 06, 2007 5:31:37 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  |