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!
Remember Me
a@href@title, strike
Powered by: newtelligence dasBlog 2.0.7226.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Michal Talaga
E-mail