How to use DebuggerTypeProxy while debugging your sensitive Type
By | August 28, 2011

Debugger in .NET runs in background on each and every type and uses Reflection to load the information regarding the Type that is running on the code. It is not generally great to view the entire object state as many of the intermediate states are not necessary to any user of your code.  Hence if you are building a library, it is your duty to enhance the Debugging experience of the application developer annotating Debugging attributes on your code. We use DebuggerHidden to hide something from the debugger, or DebuggerStepThrough to step through some code while debugging. But when you have built a complex type yourself, and not want to show what is inside of it in Debugger, you can use DebuggerTypeProxy class to create a proxy of the class which is been used and show only the portion which is important.

DebuggerTypeProxy is used to enhance the debugging experience of the user by providing a new class for the existing one allowing you to rearrange the important properties from it in Watch window rather than dealing with the pain of finding it out in the hierarchy of the type.  The most simplest example is when you want to deal with IEnumerables. It is really hard to get information of an IEnumerable. Lets add a Proxy to see how we can improve the debugging experience of the user using DebuggerTypeProxy attribute.

Say we define a class MyType which lists some string like this :

[DebuggerTypeProxy(typeof(MyProxyClass))]
public class MyType
{
public List Items { get; set; }

public MyType()
{
this.Items = this.Items ?? new List();
}

}

Here the class lists a collection of string in itself. It is better to use a comma separated string for the same rather than viewing the same thing in hierarchy. Lets do it now.

public class MyProxyClass
{
public MyType BaseType { get; set; }

public MyProxyClass(MyType basetype)
{
this.BaseType = basetype;

}
public string Items
{
get
{
return string.Join(",", this.BaseType.Items);
}
}
}

Notice the Proxy class takes the original class (in this case it is MyType) in constructor argument. Now we expose the Items here as string rather than a collection.

If we try to run our code we see something like this :
debuggerproxy How to use DebuggerTypeProxy while debugging your sensitive Type

So you can see, rather than seeing the actual Items property, we see the new property from the proxy class.

You can download the sample application

Read More from here.

I hope this would help you.

Thanks icon smile How to use DebuggerTypeProxy while debugging your sensitive Type

One thought on “How to use DebuggerTypeProxy while debugging your sensitive Type

  1. Pingback: 10 Effective Debugging Tips for .NET Developer

Comments are closed.