Friday, September 20, 2013

Customised Debugger Output using DebuggerDisplay Attributes

 

Debugger display attribute helps to customized debugger message which in turn create more meaningful debug messages.

When we try debugging the below sample code

 var order = new Order
                {
                    OrderId = Guid.NewGuid(),
                    OrderDate = DateTime.Now,
                    Amount = 100.00M,
                    Customer = new Customer()
                        {
                            Id = Guid.NewGuid(),
                            Name = "Arjit"
                        }
                };

 

 


image

when debugged the sample code above and hover the order variable we can see the name of the Type the order variable is holding. When implementing the debugger attributes the same code is seen like below in debug mode

image

Lets see How to implement this For creating custom debug messages we need to decorate class with DebuggerDisplay.
 [DebuggerDisplay("New Order is Created By {Customer.Name} on 
{OrderDate.ToShortDateString()} For ${Amount}")]
class Order
{
public Guid OrderId { get; set; }
public DateTime OrderDate { get; set; }
public decimal Amount { get; set; }
public Customer Customer { get; set; }
}
[DebuggerDisplay("New customer is {Name}")]
class Customer
{
public Guid Id { get; set; }
public string Name { get; set; }
}
If You don’t want the properties to be appearing on debug window the use
 
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public Guid Id { get; set; }