When debugging, it's common to hover over an object to get a quick view of what its properties are. With a single object this is fine because you can easily expand it to view its contents, but when you have a collection of objects it's painful to see the contents as you have to expand every element. The typical view in the debugger of a collection of simple movie classes is like this:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public float Rating { get; set; }
}
This is where DebuggerDisplayAttribute comes in; by applying it to our Movie class the collection hover can be made much more informative. The format string looks similar to normal .NET format strings in that the values to replace are between curly braces, but instead of being told what to substitute the debugger treats these values as expressions and attempts to evaluate them using the current context. Here we simply list the properties of the object:
[DebuggerDisplay("Id = {Id}, Title = {Title}, Rating = {Rating}")]
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public float Rating { get; set; }
}
Where this gets really interesting, however, is that with the C# debugger you can enter much more powerful expressions to evaluate than just the property names. If we didn't want to have really long titles listed in full (because "The assassination of Jesse James by the coward Robert Ford" might scroll off all but the widest of monitors) we could truncate them to 20 characters and show an ellipsis to indicate the truncation:
[DebuggerDisplay(
"Id = {Id}, " +
"Title = {Title.Substring(0, System.Math.Min(Title.Length, 20)) + (Title.Length > 20 ? \"…\" : \"\")}, " +
"Rating = {Rating}")]
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public float Rating { get; set; }
}
There is a down-side to this power though - because evaluation of the DebuggerDisplayAttribute format string is compiler-specific, the first example will work fine most other debuggers such as VB, but the second one will not evaluate due to its use of the C#-specific ternary operator. Depending on the debugger this will cause it to display either the default value of the class name, or an error indicating which part of the syntax could not be evaluated; this may be important if you work in a multi-language environment, or if you ship your classes as a library to customers.
Posted
Jul 28 2008, 09:44 PM
by
Greg Beech