Print Your Objects

Is there an easy way to see the internal, structural details of your objects laid out in one place so you don’t have to go searching layers and layers of objects to find what you want? Yes, there is. Let’s see how strings can make your life awesome.

As a programmer, I spend a lot of time debugging. Most of this time is spent in analyzing the state of various objects to figure out the internals of a program. Many of these objects are huge and consist of layers of objects beneath them. Sometimes, I need to see a single property which is buried deep into the object hierarchy and it’s a pain to expand all the objects to reach the deeper abstraction.

Most of the mainstream languages provide a nice mechanism to turn the objects into printable strings. Strings are great for visual analysis, you can understand the internal essentials of an object just by looking at its string representation. You can often look at the string generated by an object and instantly diagnose the problem.

As the owner of a class, you can choose which are the essential parts that constitute an object and choose to show them in the string representation of that object. In C#, this is done by overriding the ToString() method, as shown below.

public class Coordinate
{
  public int X { get; set; } 
  public int Y { get; set; }

  public override string ToString() 
  {
    return $"{X}, {Y}";
  }
}

Now, when you are debugging Coordinate, you don’t need to open you Locals window and use the drop-down to dive deeper into Coordinate. Just hover your pointer over the instance of Coordinate and boom! You have a nicely formatted string representation of Coordinate.


Click and hold to see the larger image