Page 1 of 1

Debugging tips for C#

#1 maffelu  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 190
  • Joined: 21-August 08

Posted 12 February 2011 - 01:08 AM

*
POPULAR

Debugging in C#, although much easier than in, say, PHP or C, can be a &!#@!~ and can take a lot of time. The most common way to find an error is to place a breakpoint where you think the error might arise and then follow the execution from there.


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:
Attached Image

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:
Attached Image

That's much better :bananaman:


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:
Attached Image

Hopefully this will help you in your debugging :tank: (what's up with the tank smily, DIC?)

Is This A Good Question/Topic? 12
  • +

Replies To: Debugging tips for C#

#2 chrixko  Icon User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 63
  • Joined: 25-November 08

Posted 12 February 2011 - 06:04 AM

Hi these are nice tips.
But there is an another elegant way to show relevant attributes of an object in debug-mode by using the DebuggerDisplayAttribute. ;)
With this attribute you can do something like:
[DebuggerDisplay("Name = {Name}, Age = {Age}, Street = {AddressAttributes[0]}")]
public class Person



If you run this in Debug-Mode the specified attributes are shown if you look up the value of a person object.

There are even some more debugger attributes: http://msdn.microsof...y/ms228992.aspx
Was This Post Helpful? 3
  • +
  • -

#3 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 12 February 2011 - 06:13 AM

Oh you glorious bastard. You have no idea how many hours you've saved by sharing that ToString override. So incredibly useful! How did I not know about it?
Was This Post Helpful? 0
  • +
  • -

#4 DivideByZero  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 238
  • View blog
  • Posts: 551
  • Joined: 02-December 10

Posted 12 February 2011 - 06:15 AM

Great tips, especially the writelineif() method :donatello:
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5566
  • View blog
  • Posts: 11,903
  • Joined: 02-June 10

Posted 12 February 2011 - 09:41 AM

View PostSergio Tapia, on 12 February 2011 - 06:13 AM, said:

Oh you glorious bastard. You have no idea how many hours you've saved by sharing that ToString override. So incredibly useful! How did I not know about it?

I'd bet 70% of my classes override ToString(). How else do you have complex classes like Employee or ProductLineItem, etc. give nice looking results in ListBoxes and ComboBoxes etc.?

View PostDivideByZero, on 12 February 2011 - 06:15 AM, said:

Great tips, especially the writelineif() method :donatello:


Good tutorial. Every debugging tutorial is a good thing. I'll be adding this to my list of tutorials for newbies. +1
Was This Post Helpful? 0
  • +
  • -

#6 SwiftStriker00  Icon User is offline

  • No idea why my code works
  • member icon

Reputation: 433
  • View blog
  • Posts: 1,599
  • Joined: 25-December 08

Posted 12 February 2011 - 09:53 AM

Also in VS 2010 you can set conditional break points and hit count break points. These tools can be useful in loops especially if you dont want have to step through every iteration

You can read more on the MSDN Page

a word to the wise: conditional break points wont throw compiler errors, only runtime. Also make sure you do == and not = because it will actually set the variable and never break.

The hit count break point is great in a loop because if your looping 1000 times, and your concerned with the 700th you dont want to hit continue 700 times. This break point will only break after the n-th time its been passed
Was This Post Helpful? 2
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5566
  • View blog
  • Posts: 11,903
  • Joined: 02-June 10

Posted 12 February 2011 - 10:43 AM

View PostSwiftStriker00, on 12 February 2011 - 09:53 AM, said:

Also in VS 2010 you can set conditional break points and hit count break points. These tools can be useful in loops especially if you dont want have to step through every iteration

You can read more on the MSDN Page

a word to the wise: conditional break points wont throw compiler errors, only runtime. Also make sure you do == and not = because it will actually set the variable and never break.

The hit count break point is great in a loop because if your looping 1000 times, and your concerned with the 700th you dont want to hit continue 700 times. This break point will only break after the n-th time its been passed


I will tell ya from experience that conditional breakpoints seriously slow down execution.
I was doing an image processing block, scanning all the pixels from left to right. The entire block on a big photos normally runs in 30 seconds. With the conditional breakpoint it took over two minutes just to conditionally break at row 50, column 100.

For something like that I can build a conditional break that is FAR faster

if (x == 50 && y== 100)
{
  console.writeline("something to break at");// put breakpoint here
}


Great debugging tips
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1