Saturday, 21 October 2017

DebuggerTypeProxy Attribute

Another cool attribute to save some debugging time is DebuggerTypeProxy (Namespace: System.Diagnostics). Using this attribute, you can write your own logic to interpret the object at debug time. Meaning, if you have a list of a class objects then you can project on certain property and force debugger to show the value off of this proxy class.

Below is the example where I have created a dummy model class. Using DebuggerTypeProxy attribute on this class, I am forcing debugger to display value of a property of the proxy class, which is DebuggerProxyForTestDebuggerProxy class.


    [DebuggerTypeProxy(typeof(DebuggerProxyForTestDebuggerProxy))]
    public class TestDebuggerProxy
    {
        public int DeptID;
        public string DeptName;
        public List<string> EmpNames = new List<string>(); 
    }

Proxy class:
public class DebuggerProxyForTestDebuggerProxy
    {
        TestDebuggerProxy instance;
        public DebuggerProxyForTestDebuggerProxy(TestDebuggerProxy obj)
        {
            instance = obj;
        }
        public string DeptInformation
        {
            get
            {
                return $"ID:{instance.DeptID} | DeptName:{instance.DeptName} |
                DeptEmps: {string.Join(",",instance.EmpNames)}";
            }
        }
    }

Proxy class contains the private variable of the model class(TestDebuggerProxy), constructor with a parameter of type TestDebuggerProxy(which sets the private member of the class) and it has also a member called DeptInformation which joins the properties of the private member.


Now, let's create an object of type TestDebuggerProxy in Main method.

static void Main(string[] args)
        {
 
            TestDebuggerProxy obj = new TestDebuggerProxy() { 
                 DeptID=1,
                 DeptName = "Dept 1",
                 EmpNames = new List<string> {"emp1","emp2","emp3" }
            };
            return;
        }

Now run the application in debug mode and hover your mouse over object "obj". You should see something like below.


Note that how debugger is displaying the value of the object. It is actually showing the property of the proxy class and not the actual class. You can view the actual properties of the class by expanding the Raw View.


This is really simple implementation of how it works but it can be very useful in legacy applications where you have complex objects and you need to check certain properties only while debugging the issue(s).

No comments:

Post a Comment