Overriding ToString
Starting with this simple technique, there is a way to improve even this, namely by overriding an objects ToString method.
If we take a simple application like this one:
static void Main(string[] args)
{
IList<Person> people = new List<Person>()
{
new Person(){Name = "Kalle", Age = 91},
new Person(){Name = "Lisa", Age = 26},
new Person(){Name = "Zlatan", Age = 29},
};
foreach (Person p in people)
{
//Do something
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
If we run this code an place a breakpoint by the foreach loop to examine the 'people' collection, we will see something like this:

This means we have to enter each individual Person object to make sure we got what we wanted. An easy way to speed up this kind of debugging process is to override the Person class´s ToString method:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("Name: {0}, Age: {1}", Name, Age);
//return base.ToString();
}
}
If you debug now and hover the people collection then you will see this:

That's much better
Using System.Diagnostics
Another way which can be extremely usefull but which is much less common knowledge is using the System.Diagnostics namespace and the Debug class.
With the debug class you can write data to the Output window in Visual Studio (found in the View menu, or by pressing Ctrl + W,O).
You can do several interesting things with the Debug class. You may simply output data using the WriteLine() method, but you can also write using conditions, with the WriteLineIf() method which is even more outstanding.
In the example below we are outputting all our person objects to the Output window, and if we find a senior citizen, we output that too:
Here's an example:
class Program
{
static void Main(string[] args)
{
IList<Person> people = new List<Person>()
{
new Person(){Name = "Kalle", Age = 91},
new Person(){Name = "Lisa", Age = 26},
new Person(){Name = "Zlatan", Age = 29},
};
foreach (Person person in people)
{
Debug.WriteLine("Name: " + person.Name);
Debug.WriteLineIf((person.Age > 65), "Senior citizen found!");
}
Console.Read();
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("Name: {0}, Age: {1}", Name, Age);
//return base.ToString();
}
}
And in the output window, you should see something like this:

Hopefully this will help you in your debugging






MultiQuote







|