Tuesday, April 29, 2014

Override ToString() on a object in C# to make it easier to debug!

Consider this Person class.

using System;
namespace Testing.Models
{
   public class Person
   {
      public string Name { get; set; }
      public DateTime Birthdate { get; set; }
      public int ZipCode { get; set; }
      public bool IsEligibleForRetirement { get; set; }
   }
}

 
 

Now consider debugging a dictionary where the key values are of the Person type like so:

 
 

A lot of the drilldown "heartache" may be alleviated by temporarily shoving in a ToString override.

using System;
namespace Testing.Models
{
   public class Person
   {
      public string Name { get; set; }
      public DateTime Birthdate { get; set; }
      public int ZipCode { get; set; }
      public bool IsEligibleForRetirement { get; set; }
      
      public override string ToString()
      {
         return Name;
      }
   }
}

 
 

Debugging gets easier and easier to read.

No comments:

Post a Comment