8.9. Creating Custom Debugging Displays for Your Classes
Problem
You have a set of classes that are used in your application. You would like to see at a glance in the debugger what a particular instance of the class holds. The default debugger display doesn't show any useful information for your class today.
Solution
Add a DebuggerDisplayAttribute to your class to make the debugger show you somethingyou consider useful about your class. For example, if you had a Citizen classthat held the honorific and name information, youcou ld add a DebuggerDisplayAttribute like this one::
[DebuggerDisplay("Citizen Full Name = {_honorific}{_first}{_middle}{_last}")]
public class Citizen
{
private string _honorific;
private string _first;
private string _middle;
private string _last;
public Citizen(string honorific, string first, string middle, string last)
{
_honorific = honorific; _
_first = first;
_middle = middle;
_last = last;
}
}Now, when instances of the Citizen class are instantiated, the debugger will show the information the way the DebuggerDisplayAttribute on the class directs it to. To see this, instantiate two Citizens, Mrs. Alice G. Jones and Mr. Robert Frederick Jones, like this:
Citizen mrsJones = new Citizen("Mrs.","Alice","G.","Jones");
Citizen mrJones = new Citizen("Mr.", "Robert", "Frederick", "Jones");When this code is run under the debugger, the custom display is used, as shown in Figure 8-1.
Figure 8-1. Debugger display controlled by DebuggerDisplayAttribute
Discussion
It is nice ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access