DebuggerDisplayAttribute

The DebuggerDisplayAttribute type is an attribute that controls how values are displayed in a debugger window. This attribute is valid for assembly, class, struct, enum, indexer, property, field, and delegate entities. You cannot use DebuggerDisplayAttribute on methods. When this attribute is used as an assembly-level attribute, the Target property must be assigned the name of the target type. The DebuggerDisplayAttribute type is found in the System.Diagnostics namespace.

The DebuggerDisplayAttribute type has a one-argument constructor. The single argument, which is a string, is the display value of the type in the Debug window. The value can contain an expression, which must be enclosed in curly braces: {expression}. Constants, static members, and instance members are valid in the expression. Prefix static members with the class name. The expression cannot contain pointers, aliases, or local variables.

The DebuggerDisplayAttribute type is inheritable. A derived class inherits the attribute from the base class. However, the derived class can redefine the DebuggerDisplayAttribute as required.

Figure 15-41 shows the values in a debug window for the ZClass and YClass instances without DebuggerDisplayAttribute.

A view of the ZClass and YClass instances without DebuggerDisplayAttribute applied

Figure 15-41. A view of the ZClass and YClass instances without DebuggerDisplayAttribute applied

The following code decorates the ZClass and YClass with the DebuggerDisplayAttribute type, shown in bold. ZClass is assigned the value NewName, which is overridden in the derived class. In addition, ZClass.fielda is adorned with a DebuggerDisplayAttribute attribute that contains an expression:

[DebuggerDisplay("NewName")]
class ZClass
{
    public static int test = 1;
    public virtual void MethodA()
    {
           int vara = 5, varb = 10;
           Console.WriteLine("{0} {1}", vara, varb);
       }

       public void MethodB()
       {
           Console.WriteLine("ZClass.MethodB");
           Console.WriteLine("ZClass.fielda {0}", fielda);
       }

       [DebuggerDisplay("fielda = {fielda}")]
       private int fielda = 5;
}

[DebuggerDisplay("DerivedName")]
class YClass : ZClass
{
    public override void MethodA()
    {
        Console.WriteLine("YClass.MethodA");
        Console.WriteLine("Fieldb: {0}", fieldb);
    }

    private int fieldb = 10;
}

Figure 15-42 shows the results of using the DebuggerDisplayAttribute type with ZClass and YClass.

A view of ZClass and YClass instances with DebuggerDisplayAttribute applied

Figure 15-42. A view of ZClass and YClass instances with DebuggerDisplayAttribute applied

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.249.92