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:
But it seems that the Visual Studio still uses the original method ToString()
of type Dictionary<string, string>
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;
}
}
}
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.