Debugging in Visual Studio
Stop guessing: pause your program with breakpoints, step line by line, inspect variables and find bugs fast.
Console.WriteLine everywhere works for tiny programs, but a debugger lets you pause a running program at any line and look inside it: every variable, every call.
Three kinds of errors
| Kind | When you see it | Example |
|---|---|---|
;, wrong type, typo in a name | ||
IndexOutOfRangeException, DivideByZeroException | ||
< instead of <= |
Breakpoints
The keys you will use every day
| Key | Command | What it does |
|---|---|---|
Look inside while paused
Hover over any variable to see its value in a tooltip (DataTip). You can even pin it. Locals window: all variables in the current method. Autos window: variables used on the current and previous lines. Watch window: type any variable or expression (like total / 3.0) and see its value update as you step.Call Stack window: which methods called which to get here (the stack frames you saw in the methods lesson). Double-click a frame to see its variables. Immediate window: run small expressions while paused, e.g. prices.Length.
Conditional breakpoints
i == 499 or total < 0. The debugger then pauses only when the condition is true.
When an exception is thrown
int[] data = { 1, 2, 3 };for (int i = 0; i <= data.Length; i++) // <= is the bug{ Console.WriteLine(data[i]); // debugger stops here when i == 3}1 2 3 System.IndexOutOfRangeException: Index was outside the bounds of the array.
A debugging routine that works
Reproduce the bug reliably: find the exact input that causes it. Form a guess: where could the wrong value come from? Pause before that point with a breakpoint and check your guess in Locals or Watch. Step forward until a value differs from what you expected. The bug is in the line you just ran. Fix one thing, then run again to confirm, including the inputs that worked before.
Largest(new[] { -5, -2, -9 }) returns 0. Find the bug (you can reason it through like a debugger: what is max before the loop?) and fix it.
static int Largest(int[] a) { int max = 0; foreach (int x in a) if (x > max) max = x; return max; }
Show a hint
Show the solution
static int Largest(int[] a){ int max = a[0]; // start from a real element, not 0 foreach (int x in a) if (x > max) max = x; return max;} Console.WriteLine(Largest(new[] { -5, -2, -9 }));-2
Remember
Compile errors stop the build; exceptions crash at run time; logic errors give wrong results. F9 sets a breakpoint, F5 runs to it, F10 steps over, F11 steps into. Use Locals, Watch and Call Stack to see what the program really holds. Reproduce → guess → pause → step → fix → re-test.