Monday 12 June 2017

Debugger Display Attribute

The debugger display attribute makes our life much simpler by creating a nice string representation of our objects when we debug our code. take a look at the following

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace pc.debuggerDisplayExample
{
    [DebuggerDisplay("{DebuggerDisplay()}")]
    public class Person
    {
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }
        public Person(string Name, DateTime BirthDate)
        {
            this.Name = Name;
            this.BirthDate = BirthDate;
        }
        public int GetAge()
        {
            DateTime today = DateTime.Today;
            int age = today.Year - BirthDate.Year;
            return BirthDate > today.AddYears(-age) ? --age : age;
        }

        private string DebuggerDisplay()
        {
            return $"{Name} {GetAge()}";
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            var ppl = new List<Person>();

            ppl.Add(new Person("Pawel", new DateTime(1984, 01, 31)));
            ppl.Add(new Person("Tom", new DateTime(1988, 08, 28)));
            ppl.Add(new Person("Magda", new DateTime(1984, 06, 28)));

            foreach (var p in ppl)
                Console.WriteLine(p);
        }
    }
}


See how we decorated our Person class with the "DebuggerDisplay" Attribute, we pass the name of the function we want our debugger display attribute to call which is a private function that returns a string representation of our object.

Now if we create a break point in our code and inspect our collection at the for each loop.


we see our string representations instead of just the general ToString() method being called like below


It's a nice little helper for debugging purposes.