MighMoS MighMoS - 1 year ago 142
C# Question

How to make [DebuggerDisplay] respect inherited classes or at least work with collections?

I've got a class which inherits from a

. It works well and as expected in all respects except one: when I add the
attribute. Even though looking at List has its as
[DebuggerDisplay("Count = {Count}")]
, if I so much as copy and paste that onto mine, I lose the ability to look directly at all of the MagicBeans I have without drilling into base->private members while debugging.

How do I get the best of both worlds? IE: Custom value in the value column, and Visual Studio not hiding my magic beans from me?

Answer Source

You can get the effect you need by using the DebuggerTypeProxy attribute. You need to create a class to make a debug "visualisation" of your inherited list:

internal sealed class MagicBeanListDebugView
    private List<MagicBean> list;

    public MagicBeanListDebugView(List<MagicBean> list)
        this.list = list;

    public MagicBean[] Items{get {return list.ToArray();}}

You can then declare this class to be used by the debugger for displaying your class, along with the DebuggerDisplay attribute:

[DebuggerDisplay("Count = {Count}")]
public class MagicBeanList : List<MagicBean>

This will give you the "Count = 3" message when you hover over an instance of your inherited list in Visual Studio, and a view of the items in the list when you expand the root node, without having to drill down into the base properties.

Using ToString() to specifically get debug output is not a good approach, unless of course you are already overriding ToString() for use in your code elsewhere, in which case you can make use of it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download