14. Debugging
Every program has bugs. Debugging is finding out why the code does what it does instead of what you meant. A debugger lets you pause a running program, look at every variable, and move forward one line at a time.
A buggy program
This method should return the 3 smallest numbers. The output is wrong twice: it returns the largest numbers, and it destroys the caller's list. Try to spot the bugs before reading on.
List<int> numbers = [4, 1, 6, 2, 5, 3];
var smallest = GetSmallests(numbers, 3);
Console.WriteLine($"Smallest 3: {string.Join(", ", smallest)}");
Console.WriteLine($"Original list: {string.Join(", ", numbers)}");
static List<int> GetSmallests(List<int> list, int count)
{
var result = new List<int>();
while (result.Count < count)
{
var min = GetSmallest(list);
result.Add(min);
list.Remove(min);
}
return result;
}
static int GetSmallest(List<int> list)
{
var min = list[0];
for (var i = 1; i < list.Count; i++)
{
if (list[i] > min)
min = list[i];
}
return min;
}Smallest 3: 6, 5, 4 Original list: 1, 2, 3
Breakpoints and stepping
A breakpoint is a marker on a line: when execution reaches it, the program pauses. Click in the gutter left of the line number, or press the shortcut. Then step through the code:
| Action | VS Code / Visual Studio | Rider (macOS keymap) |
|---|---|---|
| Toggle breakpoint | F9 | ⌘F8 |
| Start debugging | F5 | ⌃D |
| Step over: run the line, don't enter methods | F10 | F8 |
| Step into: enter the method on this line | F11 | F7 |
| Step out: finish this method, return to the caller | ⇧F11 | ⇧F8 |
| Continue to the next breakpoint | F5 | ⌘⌥R |
With the C# Dev Kit extension, VS Code can debug a single file like these examples: open it, set a breakpoint, press F5. If your setup can't, run dotnet project convert Buggy.cs to turn the file into a normal project.
Inspecting state
While paused, the debugger panels answer "what is going on right now?":
- Locals (Variables): every variable in the current method and its value.
- Watch: expressions you type yourself, like
list.Countorlist[i] > min, re-evaluated at every step. - Call Stack: the chain of method calls that led here. Top-level code calls
GetSmallests, which callsGetSmallest.
Put a breakpoint inside GetSmallest and watch min. It only ever grows, which points straight at the > that should be <. The second bug shows in the Watch panel too: numbers.Count shrinks with every list.Remove, because the method works on the caller's list, not a copy.
In a loop of 10,000 passes, stepping to the interesting one is painful. Right-click a breakpoint and add a condition like i == 3: it only pauses when the condition is true.
Defensive programming
Better than finding bugs is making them fail loudly and early. Guard clauses check a method's inputs at the very top and throw immediately if they are invalid, instead of crashing somewhere deeper with a confusing error.
.NET has one-line guards built in: ArgumentNullException.ThrowIfNull, ArgumentOutOfRangeException.ThrowIfNegative, ThrowIfNegativeOrZero, ThrowIfGreaterThan, and ArgumentException.ThrowIfNullOrWhiteSpace for strings. The fixed version also copies the list, so the caller's data is left untouched.
List<int> numbers = [4, 1, 6, 2, 5, 3];
Console.WriteLine($"Smallest 3: {string.Join(", ", GetSmallests(numbers, 3))}");
Console.WriteLine($"Original list: {string.Join(", ", numbers)}");
try
{
GetSmallests(numbers, 10);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Rejected: {ex.Message}");
}
static List<int> GetSmallests(List<int> list, int count)
{
ArgumentNullException.ThrowIfNull(list);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(count);
ArgumentOutOfRangeException.ThrowIfGreaterThan(count, list.Count);
var buffer = new List<int>(list);
var result = new List<int>();
while (result.Count < count)
{
var min = GetSmallest(buffer);
result.Add(min);
buffer.Remove(min);
}
return result;
}
static int GetSmallest(List<int> list)
{
var min = list[0];
for (var i = 1; i < list.Count; i++)
{
if (list[i] < min)
min = list[i];
}
return min;
}Smallest 3: 1, 2, 3
Original list: 4, 1, 6, 2, 5, 3
Rejected: count ('10') must be less than or equal to '6'. (Parameter 'count')
Actual value was 10.Start the API with the debugger attached (F5) and put a breakpoint inside an endpoint: it pauses when a request arrives, so you can inspect the incoming data. For what happens in production, where no debugger runs, inject an ILogger<T> and log instead:
app.MapGet("/orders/{id}", (int id, ILogger<Program> logger) =>
{
logger.LogInformation("Fetching order {OrderId}", id);
return Results.Ok(new { id });
});