Search code examples
c#visual-studio-2010dictionarytostringvisual-studio-debugging

Watch window in Visual Studio 2010 not working for classes inherited from generic Dictionary


I created a class that inherits from Dictionary<string, string> and overrided method ToString() for easy debugging (to see the status of an instance of this type in Watch window). If I display this type on the console, everything works:

Displaying custom type that inherited from Dictionary<string, string> in Console

But it seems that the Visual Studio still uses the original method ToString() of type Dictionary<string, string>

Displaying custom type that inherited from Dictionary<string, string> in Watch window

This fact awfully complicates debugging of my code because I can't quickly see the desired values ​​of the fields of this type.

How to force Visual Studio to use my method ToString(), not the method of type Dictionary<string, string>?

using System;
using System.Collections.Generic;

namespace TestDictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            CmdValue innerCmdVal = new CmdValue("InnerName", null);
            CmdValue cmdVal = new CmdValue("name1", innerCmdVal);
            cmdVal.Add("key1", "value1");
            Console.WriteLine(cmdVal);
            Console.ReadKey();
        }
    }

    class CmdValue : Dictionary<string, string>
    {
        public readonly string Name;
        public readonly CmdValue InnerCmdValue;

        public CmdValue(string name, CmdValue innerCmdValue)
        {
            this.Name = name;
            this.InnerCmdValue = innerCmdValue;
        }

        public override string ToString()
        {
            string str = string.Format("{0}[{1}].{2}", this.Name, this.Count, this.InnerCmdValue);
            return str;
        }
    }
}

Solution

  • You are looking for the DebuggerDisplayAttribute.

    Example:

    [DebuggerDisplay("Name: {LastName}, {FirstName}")]
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    The debugger window will show "Name: Clinton, Bill" as a value if you create a customer named Bill Clinton.