4

Overriding a class's ToString() is usually all you need to do to get custom formatting in the watch window, but when the class is derived from a list it doesn't seem to work.

class ListOfInts : List<int>
{
    public override string ToString()
    {
        return string.Join(",", this);
    }

    public static ListOfInts test = new ListOfInts() { 3, 4, 5 };
}

Inspecting 'test' in the watch window I get

ListOfInts.test             Count = 3   ListOfInts

and have to manually force the issue like so:

ListOfInts.test.ToString()  "3,4,5"     string

This is fine for a single list, but I have a large array of the things. Is there a way to stop the default "Count = 3" format from taking priority?

tombola
  • 165
  • 12

1 Answers1

2

You can use the DebuggerDisplayAttribute:

[DebuggerDisplay("{ToString()}")]
public class ListOfInts : List<int>
{
    public override string ToString()
    {
        return string.Join(",", this);
    }
}
haim770
  • 48,394
  • 7
  • 105
  • 133
  • It's interesting to know why his quick watch window didn't use the overridden `ToString`. I guess it has something to do with his debugger settings (f.e. "show raw structure on objects in variables windows"). – Tim Schmelter Oct 14 '16 at 10:16
  • @TimSchmelter, In my LinqPad it does use the overridden `ToString()` without the `[DebuggerDisplay]` attribute. Didn't check VS though. – haim770 Oct 14 '16 at 10:20
  • Could be, although that particular setting doesn't appear to make a difference. Using this attribute definitely does though -) – tombola Oct 14 '16 at 10:21
  • Note that it'll probably be a good idea to limit this to some degree, as in the case where it's a List where T is a class whose ToString() implementation is slow-executing, this might cause unwanted delays (or otherwise just stop working after it times out for the first time). Something like `return string.Join(",", this.Take(20)) + this.Count > 20 ? "..." : "";` should fix – Omer Raviv Oct 15 '16 at 08:30