Home > Net >  c# is there a DebuggerDisplay equivalent to format class members?
c# is there a DebuggerDisplay equivalent to format class members?

Time:05-26

The DebuggerDisplay attribute allows to show a custom "value" or interpretation for entire class. This is good, but is there a possibility to force also displaying a standard type member (ie. UInt32) to a hexadecimal value?

There are 2 reasons I want this

  • some of my members has meaning in hex only (addresses, bit masks)
  • the hex formatting is global in C# IDE so I have to toggle manually quite often

[DebuggerDisplay("{_value,h}")] 
public abstract class DataField
{
  [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  private UInt32 _value;
            
  // display this member in debugger permanent as HEX 
  public UInt32 ConstMask { get; set; } 
}

One option I see is to declare ConstMask as a class and apply DebuggerDisplay formatting as well, but this will affect my performances and I guess is not a good option to do that just for debug purposes.

Thanks in advance for hints,

CodePudding user response:

When you need more control/code to format your debugger display, you can use nq and the name of a property used to return the string. Like this:

[DebuggerDisplay("{DebuggerDisplay,nq}")]
public abstract class DataField
{
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private UInt32 _value;

    // display this member in debugger permanent as HEX 
    public UInt32 ConstMask { get; set; }

    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private string DebuggerDisplay =>
        $"{this.GetType().Name} 0x{this._value:X8}";
}

CodePudding user response:

You are looking for the DebuggerTypeProxyAttribute. This attribute allows you to define a type which can be expanded to show all of the properties.

[DebuggerTypeProxy(typeof(HashtableDebugView))]
class MyHashtable : Hashtable
{
    private const string TestString = "This should not appear in the debug window.";

    internal class HashtableDebugView
    {
        private Hashtable hashtable;
        public const string TestString = "This should appear in the debug window.";
        public HashtableDebugView(Hashtable hashtable)
        {
            this.hashtable = hashtable;
        }

        [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
        public KeyValuePairs[] Keys
        {
            get
            {
                KeyValuePairs[] keys = new KeyValuePairs[hashtable.Count];

                int i = 0;
                foreach(object key in hashtable.Keys)
                {
                    keys[i] = new KeyValuePairs(hashtable, key, hashtable[key]);
                    i  ;
                }
                return keys;
            }
        }
    }
}
  •  Tags:  
  • c#
  • Related