One of the alternative yet under utilized way to debug code in .NET is using Debug class found in System.Diagnostics Namespaces. This class really gives bunch of functionalities to developer that are very useful for debugging and I wonder why but I have observed that fewer percentage of developers use it. So I thought to share the usage of Debug class with developers out there as I found it very useful.
I will directly jump to code snippet demonstrating the functionality of Debug class:
using System.Collections.Generic;
using System.Diagnostics;
namespace DemoDebugClass
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public static class CustomerExtensions
{
public static void PrintCustomersBelowAge25(this IEnumerablecustomersList)
{
foreach (var customer in customersList)
{
Debug.WriteLine(string.Format("Customer Name: {0}", customer.Name));
Debug.WriteLineIf(customer.Age < 25, "Required Customer Found!");
}
}
}
class Program
{
static void Main(string[] args)
{
ListcustomersList = new List ();
customersList.Add(new Customer { Id = 1, Age = 30, Name = "Customer A" });
customersList.Add(new Customer { Id = 2, Age = 15, Name = "Customer B" });
customersList.Add(new Customer { Id = 3, Age = 20, Name = "Customer C" });
customersList.PrintCustomersBelowAge25();
}
}
}
In the above code snippet, we have a customer class and assume that we are interested in finding customers below age 25 as shown in code snippet above. With the Debug.WriteLine you can print data to Output Window in Visual Studio (View –> Output Window) and even conditional data as well, as depicts in image below.
Now this is really interesting because it gives liberty to developers to debug the program and data without using breakpoints as most of us used to do. Further these lines are only executed when the program is executed in Debug mode. Besides, this also allows you to easily share the output log with your colleagues.
So go ahead and give it a try! If you don’t use it for some reason then please share your remarks in comments below. Happy Coding!
4 Comments
zishu · April 5, 2011 at 6:25 am
thanks adil…nice stuff…keep it up please…
Regards,
Zeeshan Azad
zishu · April 5, 2011 at 6:31 am
nice stuff adil…thanks n keep it up..
Regards,
Zeeshan Azad
Zain · April 5, 2011 at 12:12 pm
I just got a sheer reminiscence of using the Immediate window for debugging VB6 Apps. Khwaari days those were, but I do agree that we certainly have started to rely lazily on the breakpoints too much…
Andolasoft · April 7, 2011 at 12:04 pm
Hi adil,
Nice blog written by you. If you have time then visit my site.