The debugger in .NET runs in the background on each type and uses Reflection to download information about the type running on the code. In general, it’s not worth looking at the full state of the object, because most of the intermediate states are unnecessary to any user of your code. Therefore, if you are creating a library, your task is to improve the application developer’s debugging experience by annotating debugging properties on your code. We use DebuggerHidden to hide something from the debugger or DebuggerStepThrough to step through code while debugging. But when you’ve built a complex type yourself and don’t want to show what it contains in the Debugger, you can use the DebuggerTypeProxy class to create a proxy of the class that was used and show only the important part.
DebuggerTypeProxy is used to improve the user’s debugging experience by providing a new class to an existing class, allowing you to rearrange its important properties in the view window instead of having to deal with difficult to find it in the type hierarchy. The simplest example is where you want to handle IEnumerables. It’s really difficult to get information about IEnumerable. Let’s add a proxy to see how we can improve the user’s debugging experience using the DebuggerTypeProxy property.
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 strings within itself. It’s better to use a comma separated string for the same thing instead of displaying the same thing in a hierarchy. Let’s 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);
}
}
}
Note that the Proxy class takes the parent class (in this case MyType) in the constructor argument. Now we display the elements here as a string instead of a collection.
If we try to run our code, we see something like this:
Here you can see, rather than viewing the actual Items property, we see the new property from the proxy class (as shown in above image).
I hope above will help. You can check more articles on our website under C# section HERE or you can also check same on Microsoft Docs too.