Using a debugger

How to:

Imagine you’ve got a tiny program that’s not acting right:

static void Main()
    int result = Sum(1, 2);

static int Sum(int a, int b)
    return a + a; // Oops, should be a + b

Using Visual Studio’s debugger, set a breakpoint by clicking on the left margin next to return a + a;. When you run the program (with F5), the execution will pause there. Hover over variables to inspect their values, or use the Immediate Window to evaluate expressions. You’ll see a is 1 and b is 2, but a + a is not our expected sum. Change it to a + b, continue running (F5), and voila, the console outputs 3.

Deep Dive

The history of debugging goes all the way back to the 1940s when a real bug (a moth) was found in an early computer. Today’s debuggers, like the one in Visual Studio, provide a suite of powerful features, including breakpoints, step-by-step execution, watch windows, and more.

Alternatives to Visual Studio’s debugger include open-source options like GDB for C-style languages or pdb for Python, and cross-platform IDEs like JetBrains Rider or VS Code which offer debugging tools for C# and other languages.

When you dive into a debugger’s implementation, you’re looking at a program that attaches to your application’s process. It interprets machine code, manages memory state, and controls execution flow. This is hefty stuff that’s crucial for effective debugging, which is why debug mode often runs slower than release mode where these hooks do not exist.

See Also