C#: Using the Debug class part 2

In the last entry I showed you how to use the System.Diagnostics namespace to write debug data to the Output window. Now we’ll use System.Diagnostics but go further by overriding the ToString() method for a class.
Normally when you debug in Visual Studio you add a breakpoint in your code and then hover the object you want to examine, it looks something like this:

Breakpoint debugging
Breakpoint

So you have to unfold every individual section of the object to check its properties. Getting the full picture quickly isn’t easy by default, but that can be changed by overriding the basic ToString() method which all objects inherit from Object.

This is an example of a standard example Person class which overrides ToString()

    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
 
        public override string ToString()
        {
            return string.Format("Name: {0}, Age: {1}", Name, Age);
        }
    }
ToString() override in debug mode
ToString() override in debug mode

But we can also do this with an attribute, namely the DebuggerDisplay attribute which does the same thing but doesn’t interfere with our implementation:

    [DebuggerDisplay("Name: {Name}, Age: {Age}")]
    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }

If you look at the list in debug mode you’ll see the same thing as with a ToString() override. The difference is that you are free to override ToString() for other purposes. Debugging should never interfere with your implementation and the attribute can be removed without any ripple effects.
In this example we get the same output, but if we create a class called Coordinate (which will represent a, well, coordinate) we want to output the coordinate like this:
14, 9 (This would be X: 14, Y: 9)
However, since we’re lousy at reading coordinates and we always forget which axis comes first (in general) we want to output “Top: 14, Left: 9” to ease our debugging experiance. Now we want different information in debugging and ToString. This is how we implement it:

    [DebuggerDisplay("Top: {X}, Left: {Y}")]
    class Coordinate
    {
        public int X { get; set; }
        public int Y { get; set; }
 
        public override string ToString()
        {
            return string.Format("{0}, {1}", X, Y);
        }
    }

One thing worth noting is that in debug mode the DebuggerDisplay attribute supersedes the ToString() implementation making DebuggerDisplay more specific when examining an object. This also applies in inheritance situations.

One thought on “C#: Using the Debug class part 2

Leave a Reply