13.2. Debugging Workflow#

Debugging is a repeatable process, not guesswork.

13.2.1. The Workflow#

Use this sequence every time:

  1. Reproduce reliably

  2. Minimize the failing case

  3. Observe state with tools

  4. Form a specific hypothesis

  5. Patch one thing

  6. 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 method

  • Step Into (F11) — follow execution into a called method

  • Step 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

i < Length - 1 instead of i < Length

Stale loop state

reusing a variable without resetting it

Null/empty assumption

skipping IsNullOrWhiteSpace check

Parsing without validation

int.Parse on unvalidated input

13.2.7. Step 6: Validate the Fix#

After patching:

  1. Re-run the original failing input

  2. Run edge cases (empty array, single element, max values)

  3. 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:

  1. Add one intentional bug (wrong field index, missing Trim)

  2. Set a breakpoint at the parse start

  3. Add a watch on parts.Length and each field

  4. Step through TryParse calls

  5. Identify the bug and fix it

  6. Re-run with both valid and malformed input

Footnotes