Freigeben über


Debugger extension in Visual Studio - Part 2

Continuing my previous post on using type proxy for extending the debugger feature in Visual Studio, I want to provide another example using two useful debugger-related attributes: DebuggerDisplay and DebuggerBrowsable. Let's review the last output on the Locals window as below.

View object properties using type proxy on Locals window 

We can substitute/re-format the value printed in second column (Value column), so for example on emp variable above, which I can replace the default {TypeProxyConsoleApp.Employee} with more friendly string. In Employee class declaration (in Employee.cs), I simply add a DebuggerDisplay attribute (see highlighted below).

    [System.Diagnostics.DebuggerTypeProxy(typeof(EmployeeTypeProxy))]

    [System.Diagnostics.DebuggerDisplay("Employee Type Proxy")]

    public class Employee 

We also can re-format the debugger output value by combining the string with the properties name enclosed with curly braces, so for example on both FullName and DaysEmployed properties in EmployeeTypeProxy.cs as shown in the code below.

        [System.Diagnostics.DebuggerDisplay("Employee's fullname is {FullName}")]

        public string FullName

        {

            get { return string.Format("{0} {1}", _employee.FirstName, _employee.LastName); }

        }

        [System.Diagnostics.DebuggerDisplay("The employee has worked for {DaysEmployed} days.")]

        public int DaysEmployed

        {

            get { return (int)((DateTime.Now.Ticks - _employee.JoinDate.Ticks) / TimeSpan.TicksPerDay); }

        } 

The second attribute is DebuggerBrowsable which controls how the variable is diplayed in the Locals/Watch window, and it is only available in C#. We can specify either of these three DebuggerBrowsableState enumerator values: Collapsed (default), Never and RootHidden. Look at MSDN for their documentation. As we see in the Locals window figure above, the Raw View tree is also showing the private fields (hence seems we seeing duplication here), and I'll use DebuggerBrowsable attribute with Never value to hide them as shown in the code below.

    [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]

        private string _firstName;

        [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]

        private string _lastName;

        [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]

        private DateTime _joinDate; 

Press F5 and once it hit the breakpoint, the Locals window output will be:

The Locals window output after using DebuggerDisplay and DebuggerBrowsable attributes

As we see from the figure above, some values have been re-formatted and those field variables are not longer displayed.

Comments