13.2. Debugging Workflow#
Debugging is a repeatable process, not guesswork.
13.2.1. The Workflow#
Use this sequence every time:
Reproduce reliably
Minimize the failing case
Observe state with tools
Form a specific hypothesis
Patch one thing
Re-test and check for regressions
13.2.2. Step 1: Reproduce Reliably#
Capture:
exact input
exact command
expected behavior
actual behavior
Without reproducibility, debugging quality collapses.
13.2.3. Step 2: Minimize the Failing Case#
Start with a buggy example — an off-by-one error in a sum loop:
// Buggy: skips the last element
int[] scores = { 85, 92, 78, 90, 88 };
int total = 0;
for (int i = 0; i < scores.Length - 1; i++) // BUG: should be <= or just <
total += scores[i];
Console.WriteLine($"Total: {total}"); // prints 345 instead of 433
Console.WriteLine($"Count: {scores.Length}");
Fix: change the loop condition to i < scores.Length:
int[] scores = { 85, 92, 78, 90, 88 };
int total = 0;
for (int i = 0; i < scores.Length; i++)
total += scores[i];
Console.WriteLine($"Total: {total}"); // 433
Console.WriteLine($"Average: {total / (double)scores.Length:F1}"); // 86.6
13.2.4. Step 3: Breakpoints and Stepping in VS Code#
Set a breakpoint before the suspected line
Step Over (
F10) — execute one line, staying in current methodStep Into (
F11) — follow execution into a called methodStep Out (
Shift+F11) — exit the current method
Set the breakpoint on the total += scores[i] line and watch total after each iteration.
13.2.5. Step 4: Watch and Call Stack#
Inspect:
key variables before and after transformations
the call stack to confirm control flow assumptions
branch conditions at decision points (
if, loop bounds)
Add a Watch expression for scores[i] and total to see each step.
13.2.6. Step 5: Typical Bug Patterns#
Pattern |
Example |
|---|---|
Off-by-one |
|
Stale loop state |
reusing a variable without resetting it |
Null/empty assumption |
skipping |
Parsing without validation |
|
13.2.7. Step 6: Validate the Fix#
After patching:
Re-run the original failing input
Run edge cases (empty array, single element, max values)
Run unit tests if they exist
// Edge case: single element
int[] single = { 42 };
int t = 0;
for (int i = 0; i < single.Length; i++) t += single[i];
Console.WriteLine(t); // 42
// Edge case: empty array
int[] empty = {};
int t2 = 0;
for (int i = 0; i < empty.Length; i++) t2 += empty[i];
Console.WriteLine(t2); // 0
13.2.8. Practice#
Take a method that parses a CSV line:
Add one intentional bug (wrong field index, missing
Trim)Set a breakpoint at the parse start
Add a watch on
parts.Lengthand each fieldStep through
TryParsecallsIdentify the bug and fix it
Re-run with both valid and malformed input
Footnotes