Skip to content
Tutorials Center
My learning

Topics

Lesson 156 of 182 ยท Testing and Quality

Debugging and Diagnostics

Learn to debug C# programs - breakpoints, reading stack traces, Debug.Assert, Trace listeners, caller info, Activity tracing, Meter metrics and the dotnet-counters, dotnet-trace and dotnet-dump tools.

Every program has bugs, and finding them is a skill you can learn. Beginners often guess: change a line, run, hope. Professionals work like detectives. They reproduce the problem, observe what the program really does, form a hypothesis, test it and fix the cause rather than the symptom. This lesson gives you the observation tools .NET provides: the interactive debugger, stack traces, assertions, trace output, and the modern diagnostics APIs (Activity and Meter) that production systems use to explain themselves.

Our online editor has no debugger and cannot attach tools such as dotnet-trace, so some parts are read-only and clearly labelled. Everything that can run here does run, and every output you see below is real.

The debugging loop

  1. Reproduce. Find the smallest input that triggers the bug, ideally as a failing test.
  2. Locate. Narrow down where the program's state first becomes wrong. Is the input already wrong when the method starts? Is the output wrong when it ends? Bisect: check the middle, then half again.
  3. Understand. Read the code and the evidence. Say out loud why the failure should be impossible; the place where your belief and reality differ is the bug.
  4. Fix and verify. Change one thing, rerun the reproduction, keep the test.

The tools in this lesson help with step 2. The most important one is free: the stack trace.

Reading stack traces

When an exception is not handled, the runtime prints the exception type, its message and the stack trace: the chain of method calls that were active when it happened, newest first. Reading it well solves a large share of bugs without any debugger.

Here is a program that fails on purpose. The line numbers refer to main.cs in the editor:

C# An unhandled exception (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output starts with Start, 6 and 8, then the runtime prints:

TEXT
Unhandled exception. System.FormatException: The input string 'x' was not in a correct format.
   at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
   at System.Int32.Parse(String s)
   at Report.Double(String text) in main.cs:line 17
   at Report.Print(String[] values) in main.cs:line 9
   at Program.<Main>$(String[] args) in main.cs:line 2

How to read it:

  • The first line names the exception type and says why: FormatException, the text 'x' is not a number.
  • Read from the top down for "where", and look for the first line that is your code. The top frames (System.Number..., System.Int32.Parse) are .NET's own code. The first frame in your file is Report.Double ... line 17. That is where your code called the failing method. Often the bug is the value passed in, not the framework method.
  • Reading downward is the call history. Double was called by Print at line 9, which was called by the top-level statements (Program.<Main>$) at line 2. The value x came from the array passed on line 2.
  • The output between the first two numbers and the failure also tells you something: "6, 8" were processed, so the bug was triggered by the third element.

Line numbers and file names come from a PDB file next to the assembly. In Release builds without symbols, you only see method names. Ship symbols (or upload them to your error tracker) so production traces are readable.

Inner exceptions and throw;

Exceptions can wrap other exceptions. The wrapper's message is for the caller; the inner exception holds the original cause. ex.ToString() prints the whole chain. The next program shows the chain and also the difference between throw; and throw ex;:

C# Inner exceptions and rethrowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

With throw; the trace still mentions Rethrower.Fail, the place the problem began. With throw ex; the trace restarts at the throw ex; line inside Run, and the real origin is lost. Always use throw; to rethrow, or wrap with new Exception(message, innerException) as LoadSettings does. More in exceptions and custom exceptions.

Breakpoints and the interactive debugger

A debugger pauses your running program so you can look inside it. This is the most powerful tool for step 2 of the loop, and it needs an IDE, so this section is read-only. Visual Studio, JetBrains Rider and Visual Studio Code with the C# extension all work in the same way.

Core actions:

Action What it does Typical key (VS / Rider)
Breakpoint Pause before the marked line runs F9
Start debugging Run with the debugger attached F5
Step over Run the current line, treating a method call as one step F10
Step into Enter the method called on this line F11
Step out Run until the current method returns Shift+F11
Continue Resume until the next breakpoint F5

While paused you can:

  • Read local variables and hover over expressions to see their values.
  • Use a Watch window to track an expression like orders.Count(o => o.Total > 100) across steps.
  • Inspect the Call Stack window (the same list as a stack trace, but you can click a frame to see its variables).
  • Evaluate code in the Immediate window or debug console, and even change a variable's value to test a theory.
  • Set conditional breakpoints: pause only when i == 9999 or customer.Name == "Ana". In a loop of a million items this is the only practical approach.
  • Use tracepoints (logpoints): print a message such as order {order.Id} total={order.Total} when the line is hit, without pausing and without editing code.
  • Turn on exception breakpoints to pause the instant an exception is thrown (first chance), not after it has bubbled to the top.

For VS Code, the C# extension generates a launch.json like this:

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Launch",
      "type": "coreclr",
      "request": "launch",
      "program": "${workspaceFolder}/bin/Debug/net10.0/MyApp.dll",
      "cwd": "${workspaceFolder}",
      "console": "internalConsole",
      "stopAtEntry": false
    }
  ]
}

Debug builds (the default for dotnet build) keep variables alive and avoid inlining so stepping makes sense. In Release builds the JIT optimizes aggressively, so a variable may be shown as "optimized away" and stepping jumps around. Debug in Debug, measure in Release.

You can also pause from code with System.Diagnostics.Debugger.Break() (only does something when a debugger is attached) and check Debugger.IsAttached. The attributes [DebuggerDisplay("...")] (what the variable looks like in the watch window), [DebuggerStepThrough] (skip trivial methods when stepping) and [DebuggerBrowsable] customize the experience.

Debug.Assert: catching your own mistakes early

An assertion states something that must be true if your code is correct. Debug.Assert(condition, message) documents an assumption and stops the program immediately, right at the point where the assumption broke, instead of letting a wrong value travel through the program and cause a mysterious failure later.

Two details matter:

  1. Debug.* calls are marked [Conditional("DEBUG")]. In a Release build the compiler removes the calls entirely, arguments included. Never put real work in an assertion condition.
  2. Assertions are for programmer errors (bugs), not for bad user input or I/O failures. Validate those with if and exceptions (validation and contracts).

The editor compiles in a configuration where the DEBUG symbol is off, so the calls vanish. You can turn them on for a file with #define DEBUG as the very first line. A failing assertion then ends the program:

C# A failing Debug.Assert (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first call prints 20. The second hits the assertion and the process stops with Process terminated., Assertion failed., your message Average needs at least one number and a stack trace whose first line is the Average method at main.cs:line 10. Without a debugger attached, a failed .NET assertion terminates the process; with one attached, the debugger breaks on that line. Remove #define DEBUG and the same program prints 20 and then NaN (0 / 0 as double) and never reached, which shows why an assertion is useful: it points at the real problem instead of a silent wrong answer.

Do not use Debug.Assert to validate public method arguments or external data. In Release builds it does nothing, so the check disappears exactly when real users arrive. Use ArgumentNullException.ThrowIfNull, ArgumentOutOfRangeException.ThrowIfNegative and similar helpers.

Debug and Trace output with listeners

Debug.WriteLine and Trace.WriteLine send text to trace listeners. By default the listener writes to the debugger's Output window. You can add others (console, file, or your own). Differences:

  • Debug.* is only compiled in with DEBUG defined (Debug builds).
  • Trace.* is compiled in when TRACE is defined, which is the default for both Debug and Release builds of normal projects.

Writing a custom listener shows the pipeline: every Write, Fail and Assert goes through the listeners.

C# A custom trace listener

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The captured list has five entries: three messages, the failed assertion, and the last message. The WriteLineIf(false, ...) line is never written, and the first Trace.Assert passes silently because its condition is true. Trace.Assert with a custom listener does not stop the program: the listener decides what to do with the failure (here it just records it). That is how production systems turn assertions into log entries instead of crashes. In real applications you configure listeners in app.config, or, far more commonly today, use ILogger rather than Trace.

Caller information: who called me?

Logging and validation helpers need to know where they were called from. Three attributes let the compiler fill in default arguments for you, at no run-time cost:

  • [CallerMemberName]: the name of the calling method or property.
  • [CallerFilePath] and [CallerLineNumber]: source file and line.
  • [CallerArgumentExpression("param")]: the source text of the argument passed to another parameter. This is how ArgumentNullException.ThrowIfNull(order) knows to say Value cannot be null. (Parameter 'order').
C# Caller info attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The failing checks print the exact source text of the condition, so you never have to write a message by hand. Assertion libraries use this to show Expected retries > 5 in test reports. Log prints [Run] because Worker.Run is the method that called it. (A call made directly from top-level statements would report <Main>$.)

Activities: tracing a request across code

A log line tells you that something happened. A trace tells you how long each part of an operation took and how the parts nest, even across services. .NET's tracing model is built into the BCL as System.Diagnostics.Activity, and it is the foundation of OpenTelemetry for .NET.

  • An ActivitySource is a named factory for activities, one per library or component.
  • An Activity represents one operation (a "span"): it has a name, start and end time, tags (key-value details) and a parent. Starting an activity inside another makes it a child.
  • An ActivityListener (or OpenTelemetry) subscribes to sources. If nobody listens, StartActivity returns null and costs almost nothing, which is why libraries such as ASP.NET Core and HttpClient emit activities all the time.
C# Activities and an ActivityListener

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Children finish first, so ReserveStock and ChargeCard are listed before PlaceOrder; each reports PlaceOrder as its parent. The parent link is held in Activity.Current, which flows through async calls automatically (async and await). In production a listener such as the OpenTelemetry exporter sends these spans to Jaeger, Zipkin, Azure Monitor or similar, and you see a timeline for every request with the slow step highlighted. Timings and IDs are available too (a.Duration, a.TraceId), but they differ on every run, so this example prints only stable facts.

DiagnosticSource / DiagnosticListener is the older, lower-level sibling used inside the framework for rich, in-process events (for example EF Core and ASP.NET Core publish events through it). Reach for Activity first.

Metrics: counting what happens

Where traces show single operations, metrics show aggregates: requests per second, queue length, bytes written. The System.Diagnostics.Metrics API provides instruments: Counter<T> (only goes up), UpDownCounter<T>, Histogram<T> (distribution of values like durations) and observable gauges. A Meter groups instruments. As with activities, recording is nearly free when nobody listens.

C# A Meter, a Counter and a MeterListener

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each tag combination (country=DE, country=FR) is tracked separately, which is what lets a dashboard draw one line per country. Keep tag values to a small, bounded set (country, status code, route template). A tag like a user ID or full URL creates millions of series and can bring a metrics system to its knees.

Production tools: dotnet-counters, dotnet-trace, dotnet-dump

When the problem happens in a running process you cannot pause (a server, a container), the .NET diagnostics tools attach to it from outside. They are installed as .NET global tools and need a real machine, so the following is read-only and shows what you would type and see:

Terminal
# Install once (on your machine)
dotnet tool install --global dotnet-counters
dotnet tool install --global dotnet-trace
dotnet tool install --global dotnet-dump

dotnet-counters ps                                   # list .NET processes and their ids
dotnet-counters monitor --process-id 12345           # live view of runtime metrics
dotnet-counters monitor -p 12345 Shop.Orders         # your own Meter, by name

A typical monitor screen (values change every second):

TEXT
Press p to pause, r to resume, q to quit.
    Status: Running

[System.Runtime]
    % Time in GC since last GC (%)                          0
    Allocation Rate (B / 1 sec)                       245,760
    CPU Usage (%)                                          12
    Exception Count (Count / 1 sec)                         0
    GC Heap Size (MB)                                      41
    ThreadPool Queue Length                                 0
[Shop.Orders]
    orders_placed (orders / 1 sec)                          7
Tool Question it answers
dotnet-counters What are CPU, memory, GC, thread pool and my own metrics doing right now?
dotnet-trace Where is the CPU time going? (records events to a .nettrace file for PerfView, Visual Studio or Speedscope)
dotnet-dump What was in memory when the process hung or crashed? (collect, then analyze with commands like clrstack, dumpheap -stat)
dotnet-gcdump Which objects hold the most memory? (a lighter heap snapshot)
dotnet-monitor The same data exposed over HTTP for containers and Kubernetes

Typical recipes:

Terminal
dotnet-trace collect --process-id 12345 --duration 00:00:30    # 30 seconds of CPU samples
dotnet-dump collect --process-id 12345                          # hang? capture a dump
dotnet-dump analyze core_20251001_101530
> clrstack            # managed stacks of the current thread
> threads             # list threads
> dumpheap -stat      # which types use the most memory

Read these results together with garbage collection and measuring performance.

A practical checklist

  • Read the whole error message and the first frame in your code before changing anything.
  • Make the failure repeatable (a test) before you debug it. Intermittent bugs usually mean threads, time or shared state (synchronization).
  • Log at boundaries (input received, external call made, decision taken) with structured logging, so production tells you what happened without a debugger.
  • Assert your assumptions with Debug.Assert in development and validate real input with exceptions.
  • Count and trace with Meter and Activity so you can see problems in production.
  • Change one thing at a time. If two changes fix it, you do not know which one mattered.
  • Fix the cause, not the symptom. Catching an exception and ignoring it hides the bug; it does not remove it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a stack trace, which frame is usually the best place to start looking for your own bug?

    The top frames are often framework code that rightly threw. The first frame in your code shows where you made the failing call, and the frames below show how execution got there.
  2. 2. Why should you rethrow with 'throw;' instead of 'throw ex;'?

    Rethrowing the same exception object with 'throw ex;' resets the stack trace, hiding where the problem really began.
  3. 3. What happens to a Debug.Assert call in a Release build?

    Debug methods are [Conditional("DEBUG")]. When DEBUG is not defined the compiler omits the calls, so assertions must never contain required side effects or input validation.
  4. 4. What does ActivitySource.StartActivity return when no ActivityListener is interested in the source?

    With no listener, StartActivity returns null. That is why the idiom is activity?.SetTag(...), and why tracing costs almost nothing when it is switched off.
  5. 5. Which tool captures a snapshot of a hung process's memory so you can analyze it later?

    dotnet-dump collect writes a memory dump of the process, and dotnet-dump analyze lets you inspect threads, stacks and heap contents. dotnet-counters only shows live metrics.

Summary

  • Debug by reproducing, locating, understanding and fixing; a failing test is the best reproduction.
  • A stack trace lists the active calls newest first; find the first frame in your code. throw; preserves it, throw ex; resets it, and InnerException holds the original cause.
  • IDE debuggers add breakpoints, stepping, watches, conditional breakpoints, tracepoints and exception breakpoints; they need Debug builds to be accurate.
  • Debug.Assert checks your own assumptions in Debug builds and disappears in Release; never use it to validate input.
  • Debug and Trace write to listeners you can customize, but most apps use ILogger.
  • Caller info attributes give helper methods the caller's name, file, line and argument text.
  • Activity and ActivitySource describe operations as nested spans; Meter, Counter<T> and Histogram<T> record numbers. Both are almost free when nobody listens and are the base of OpenTelemetry.
  • dotnet-counters, dotnet-trace and dotnet-dump examine running processes from outside.

Next: Analyzers, Code Style and Warnings