Web Design that taps into the haromny and vision of your dreams.

Using the Visual Studio Debugger

Using the Debugger

Written By on in C#

1,086 words, estimated reading time 5 minutes.

Visual Studio and the Express editions all have a very powerful debugging tool which features a step-through debugger, watch list and call stack among other features. These are all essential tools for debugging and testing applications.

Using Visual Studio Series
  1. Getting Started with Visual Studio
  2. Using the Visual Studio Integrated Development Environment
  3. Using the Visual Studio Debugger
  4. XML Documentation in Visual Studio
  5. Using Microsoft .Net Command Line Tools
  6. What is an Assembly in Microsoft .Net?
  7. Creating and Using a .NET Assembly in C#
  8. Creating and Implementing Satellite Assemblies
  9. Creating Strong Named Assemblies in Microsoft .Net
  10. Visual Studio Task List
  11. Resources and Localisation in C# Projects
  12. Localising Microsoft .Net Applications with C#
  13. Using Resource Files in C# Applications
  14. Using XSD Tool to Generate Classes from XML
  15. 10 Visual Studio Tools You May Not Know About

This article relates to an old version of the .Net Framework. While the contents are still relevant, future versions of the framework may change, or improve upon, the contents of this article.

The most basic feature of the debug environment is breakpoints. When the program is run in debug mode the application will pause and return to the editor when it hits a breakpoint. This will allow you to see what the program is doing at that stage of execution. You can step through the code to see where the flow of execution moves; you can inspect variables, view the call stack and evaluate expressions.

Breakpoints

Breakpoints can be set in a number of ways, the easiest of which is to click on the gutter (the grey area to the left of the code editor). This will make the line highlight red with a circle in the gutter. You can only set a breakpoint on a valid line of executable code. You can also right click on the code line and set a breakpoint or you can use the Debug menu to add breakpoints. They can be removed in the same way as you added them.

Breakpoints in action
Breakpoints in action

When you run the program in debug mode (F5) the program will pause just before the breakpoint and return to the code editor window. From here you can now investigate the cause of the problem, either by interrogating the variables or stepping through the code. You can see the contents of a variable, object or class by hovering over the variable with the mouse. The editor will pop-up a window containing detailed information about the object. We will cover interrogating variables more in the "Watches" section below.

Breakpoint variable investigation
Breakpoint variable investigation

You can step through the code in a number of different methods, you can step through line by line using F11, step over using F10 or step out using (Shift+F11).

Step Through: Each and every line of code executed will be debugged. When a method call is invoked the flow enters the method and returns to the calling line after it has completed.

Step Over: As above, however you will not debug internal method calls. This is a better debug tool if you already know that a method is working and just wasn't to call it without debugging.

Step Out: If you entered a method using Step Through, Step Out will return you to the point that method was called.

Have a play with the debugger using this code:

using System;
 
class Program
{
  static void Main()
  {
    int a = testMethod1();
    int b = testMethod2();
    Console.WriteLine(a + b);    
  }
 
  public int testMethod1()
  {
    int x = 1;
    int y = 2;
    return (x * y);
  }
 
  public int testMethod2()
  {
    int x = 5;
    int y = 10;
    return (x + y);
  }
}

Set a breakpoint on the call to testMethod1 in Main. Start debugging using F5 and step through the program. Have a go at investigating variables with the mouse. Step through the code and see how the flow moves into testMethod1, back to main and then into testMethod2.

Close the program and start debugging again, this time use the step over and notice the difference? The debugger only stops on each line of Main, but steps over the code inside the methods.

Start debugging again (last time) and step into again. When you get inside testMethod1, use step out to return to the main method.

Conditional Breakpoints

By default a breakpoint will stop program execution every time they are hit. You can however set a breakpoint to only stop when a certain condition is met. By right clicking on the breakpoint you can add conditions so that if the condition is not met then the debugger will not stop at the breakpoint. You can also tell the debugger to perform additional actions when a breakpoint is triggered, like displaying a message or running a macro. You can also view the "hit count" which is useful when debugging a iteration or recursive method.

Watches, Auto's and Locals

Watches, Auto's and Locals are windows that are available during debug. You can add a "watch" which will display the value of the selected variable into the watches window and you can see how the value changes as you step through the code. This is particularly useful for debugging a recursive or iterative method as you can see how all the values interact, or look at the loop counter and so on.

Auto's and locals are automatically generated watch lists and contain the variables available in the current context.

One of the more useful features of auto's and watches is that you can modify the contents of a variable during debug. When inspecting a variable you can right click on it and select "Edit Value". Hitting enter will update the value and allow you to continue testing with a different value.

Debug Class

Microsoft .Net contains a class called Debug which you can use to log debug messages to the output window. These debug messages will only be available while the program is running under debug mode in the IDE. If it is compiled under release these debug messages are removed.

To use the Debug class, simply add "using System.Diagnostics;" to your uses section and call Debug.Write:

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Diagnostics;
 
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Image image = Bitmap.FromFile("c:\breakpoints.png");
 
            if (image.Height > 100)
            {
                Debug.Write("Image height is too large");
            }
            else
            {
 
            }
        }
    }
}

In addition to Write, you call WriteIf, WriteLine and WriteLineIf. WriteIf and WriteLineIf will only write the debug message if the condition is met. WriteLine appends a line terminator to the message.

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Diagnostics;
 
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Image image = Bitmap.FromFile("c:\breakpoints.png");
 
            Debug.WriteIf(image.Height > 100, "Image height is too large");
        }
    }
}
Debug.Write example
Debug.Write example

Immediate Window

The immediate window is a very powerful tool for debugging as it allows you to not only inspect variables and method return values, but to also construct and execute statements. Virtually any single line statement can be run, inspected and modified.

Visual Studio Immediate Window
Visual Studio Immediate Window

This can be particularly useful when trying to format a string, or counting indexes for substring as shown above. You can make quick changes easily to get the desired result without having to recompile.

Last updated on: Wednesday 27th June 2018

 

Comments

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me