One of the alternatives yet underutilized way to debug code in .NET is using
Debug
class found in
System.Diagnostics
Namespaces. This class really gives a bunch of functionality to developers that are very useful for debugging and I wonder why but I have observed that fewer percentage of developers use it. So I thought of sharing the usage of
Debug
class with developers out there as I found it very useful.
I will directly jump to the 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 IEnumerable<customer> customersList)
{
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)
{
List<customer> customersList = new List<customer>();
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
customer
s below age 25 as shown in the 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 depicted in the 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. Happy coding!