<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Arrays and methods
All lessons in this course

Lesson 16 of 60 13 minBeginner

Debugging in Visual Studio

Stop guessing: pause your program with breakpoints, step line by line, inspect variables and find bugs fast.

Every programmer writes bugs. Good programmers find them quickly. Adding 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

KindWhen you see itExample
Compile errorBefore the program runs (red squiggles, Error List)missing ;, wrong type, typo in a name
Runtime exceptionThe program crashes while runningIndexOutOfRangeException, DivideByZeroException
Logic errorIt runs but gives the wrong answerwrong loop start, integer division, < instead of <=

Logic errors are the hardest because nothing tells you about them. The debugger is the tool for exactly this. Try it: the program below should print an average of 133.33, but it doesn’t.

Interactive

Find the bug with the debugger

The average of 120, 80 and 200 should be 133.33, but this program prints something else. Click line numbers to toggle breakpoints, press Start, then step and watch the variables.

Breakpoints:
Average.cs
int[] prices = { 120, 80, 200 };int total = 0; for (int i = 1; i < prices.Length; i++){    total += prices[i];} double average = total / prices.Length;Console.WriteLine($"Average: {average}");
Locals
NameValue
Not running
Set at least one breakpoint (try line 6), then press Start. Without breakpoints the program just runs to the end.

Breakpoints

A breakpoint tells the debugger: “pause here, before running this line”. In Visual Studio click in the grey margin left of a line, or press F9. A red dot appears. Then start with F5 (Start Debugging).

The keys you will use every day

KeyCommandWhat it does
F5Start / ContinueRun until the next breakpoint (or the end)
F9Toggle BreakpointAdd or remove a breakpoint on the current line
F10Step OverRun the current line, including any method it calls, and pause on the next line
F11Step IntoIf the line calls your method, go inside it
Shift+F11Step OutFinish the current method and pause back in the caller
Shift+F5Stop DebuggingEnd the program
Ctrl+F10Run to CursorRun until the line where your cursor is

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

If a bug happens only on the 500th loop iteration, stopping 500 times is painful. Right-click the red dot → Conditions and enter something like i == 499 or total < 0. The debugger then pauses only when the condition is true.

When an exception is thrown

While debugging, an unhandled exception pauses execution on the exact line that failed and shows the Exception Helper: the exception type, its message and a “View Details” link with the stack trace. Read the message carefully. It usually names the problem exactly.

Crash.cs
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}
Output
1
2
3
System.IndexOutOfRangeException: Index was outside the bounds of the array.

A debugging routine that works

  1. Reproduce the bug reliably: find the exact input that causes it.
  2. Form a guess: where could the wrong value come from?
  3. Pause before that point with a breakpoint and check your guess in Locals or Watch.
  4. Step forward until a value differs from what you expected. The bug is in the line you just ran.
  5. Fix one thing, then run again to confirm, including the inputs that worked before.
Quick check

You are paused on a line that calls your own method CalculateTax(). Which key goes inside that method?

Quick check

A program runs without crashing but prints a wrong total. What kind of error is this?

Practice

This method should return the largest number in an array, but 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

Step through it mentally with the input -5, -2, -9. Is any number greater than the starting value of max?

Show the solution
Solution.cs
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 }));
Output
-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.
0 of 60 lessons completed