AI Code Review in C#: Claude Haiku vs .NET Analyzers

Last updated: November 16, 2026 · Tested with Claude Code 2.1.325 (headless, Claude Haiku), .NET SDK 10.0.401, Microsoft.VisualStudio.Threading.Analyzers 18.12.1, IDisposableAnalyzers 4.0.8, Windows 11

Short answer: I planted six bugs in a small C# pull request and gave it to two reviewers: Claude Code in headless mode (claude -p) with the small Haiku model, and the free .NET analyzers in dotnet build. Haiku found all six in three of four runs, and five and a half in the fourth. The SDK analyzers found three, but only once I set AnalysisLevel to latest-all, and they buried them under 19 other warnings. Two free NuGet analyzer packages took them to five of six. Nothing static found the off-by-one in the paging code. All four AI reviews together cost $0.0118 as reported by the CLI. My setup: the analyzers as a hard build gate, the AI review as advisory comments.

This post used to show how to build your own reviewer on the OpenAI API. I never ran that code, so I replaced it with a measured test. Here’s the result per bug:

Planted bug Claude Haiku (4 runs) SDK analyzers, default latest-all + 2 free NuGet analyzers
async void method 4/4 no no VSTHRD100
Missing await 4/4 CS4014 CS4014 CS4014
Off-by-one in 1-based paging 4/4 no no no
SQL built by string concatenation 4/4 no CA2100 CA2100
HttpClient disposed before the request finishes 3/4, plus 1 partial no no IDISP013
!= null || instead of && 4/4 CS8602 CS8602 CS8602
Other findings 0–8 per run, 1 wrong 0 19 warnings 19 warnings

The Test Pull Request

The repo is a small net10.0 class library with nullable enabled. The main branch has an OrderService with a parameterized SQL count and an injected HttpClient. The feature/receipts branch is the “PR”. It turns GetTotal into a LINQ Sum (a correct refactor, to see if anyone complains about it), adds two methods to OrderService and a new ReceiptService. The diff the reviewers saw is 84 lines. These are the planted bugs:

public async void SendReceipt(Order order, decimal total)
{
    if (!HasValidEmail(order.Customer))
        return;
    await email.SendAsync(order.Customer.Email!, $"Receipt {order.Id}", $"Total: {total:C}", CancellationToken.None);
}

public async Task CompleteAsync(Order order, CancellationToken ct)
{
    audit.WriteAsync($"Order {order.Id} completed", ct);
    await email.SendAsync("ops@example.com", "Completed", order.Id, ct);
}

public static bool HasValidEmail(Customer customer)
{
    if (customer.Email != null || customer.Email.Contains('@'))
        return true;
    return false;
}

public static Task<string> DownloadInvoiceAsync(string url)
{
    using var client = new HttpClient();
    return client.GetStringAsync(url);
}
public async Task<int> CountBySkuAsync(string sku, CancellationToken ct)
{
    await using var cmd = connection.CreateCommand();
    cmd.CommandText = "SELECT COUNT(*) FROM OrderLines WHERE Sku = '" + sku + "'";
    return Convert.ToInt32(await cmd.ExecuteScalarAsync(ct));
}

/// <summary>Returns one page of orders. <paramref name="page"/> is 1-based.</summary>
public static IReadOnlyList<Order> GetPage(IReadOnlyList<Order> orders, int page, int pageSize) =>
    orders.Skip(page * pageSize).Take(pageSize).ToList();

To be sure the less obvious ones are real bugs and not style opinions, a small console app calls them. Real output:

GetPage(page: 1, size: 2): o3, o4
HasValidEmail(dev@example.com): True
HasValidEmail(not-an-email): True
HasValidEmail(null): NullReferenceException
DownloadInvoiceAsync: TaskCanceledException: A task was canceled.

Page 1 returns the second page. The email check accepts any non-null string and throws on null. And the invoice download never works: the using disposes the client when the method returns the task, which cancels the request that is still in flight (the test server answers after 500 ms). This is the bug I most wanted to test. It looks fine at a glance, and it’s different from the usual “don’t create an HttpClient per call” advice. For that one, see HttpClient in .NET 10 with IHttpClientFactory.

What the .NET Analyzers Found

First, a plain dotnet build with SDK defaults. Only the compiler warnings fire:

ReceiptService.cs(24,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
ReceiptService.cs(30,39): warning CS8602: Dereference of a possibly null reference.

That’s two of six for free, if your build doesn’t hide warnings. CS8602 only fires because nullable is enabled. It points at the right spot, but it says “possibly null”, not “this check accepts any string”.

Then dotnet build -p:AnalysisLevel=latest-all, which turns on every rule in the built-in Microsoft analyzers (see code analysis in .NET). It printed 22 warnings. One more of them is a planted bug:

OrderService.cs(24,9): warning CA2100: Review if the query string passed to 'string DbCommand.CommandText' in 'CountBySkuAsync', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)

The other 19 were CA2007 (ConfigureAwait) six times, CA1062 (null-check public parameters) four times, CA1305 and CA2234 twice each, and CA1002, CA1822, CA1307, CA1054 and CA1716 once. Five of the 19 were on lines the PR didn’t touch. None of them is wrong, but if you switch on latest-all in an existing project you’ll see three useful warnings among 22.

The SDK has no rule for async void or for the disposed client. Two free NuGet packages do: Microsoft.VisualStudio.Threading.Analyzers (VSTHRD rules) and IDisposableAnalyzers (IDISP rules). With both added, the build printed 24 warnings. The two new ones were both planted bugs:

ReceiptService.cs(15,23): warning VSTHRD100: Avoid "async void" methods, because any exceptions not handled by the method will crash the process (https://microsoft.github.io/vs-threading/analyzers/VSTHRD100.html)
ReceiptService.cs(38,16): warning IDISP013: Await in using (https://github.com/DotNetAnalyzers/IDisposableAnalyzers/blob/master/documentation/IDISP013.md)

That’s five of six. The paging bug is the one no rule can see, because the code is valid. Only the XML comment says page is 1-based. dotnet format --verify-no-changes exited with 0 and changed nothing. It’s a formatting check, not a bug finder.

What Claude Code (Haiku) Found

I ran four reviews with Claude Code 2.1.325 in headless mode. The CLI’s haiku alias resolved to claude-haiku-5-5. Three runs got the diff on stdin with no tools at all. The fourth ran inside the repo with read-only tools and was allowed to call git diff itself. The command for diff mode (the headless mode docs list the flags):

claude -p "$(cat prompts/plain.txt)" --model haiku --tools "" --output-format json --max-budget-usd 0.50 < pr.diff > review.json

The two prompts were short and didn’t name any of the bugs. The plain one:

Review this pull request diff for a C# library (.NET 10, nullable enabled). List every bug or risk you find. For each one give the file, the line, a severity (high/medium/low) and a one-line fix. Be concise.

The “bugs only” one adds: “Report only problems that will cause wrong results, crashes, security holes or resource leaks at run time. No style, naming or ConfigureAwait comments. If you are not sure something is a bug, leave it out.” Here is that run’s full answer, unedited:

| # | File:line | Severity | Problem | One-line fix |
|---|---|---|---|---|
| 1 | `src/Orders/OrderService.cs:24` | high | `sku` is concatenated into the SQL text, so a crafted value injects SQL. | Use a parameter: `cmd.Parameters.AddWithValue("@sku", sku)` and set `CommandText` to `... WHERE Sku = @sku`. |
| 2 | `src/Orders/ReceiptService.cs:30` | high | `customer.Email != null \|\| customer.Email.Contains('@')` is wrong. A null email throws `NullReferenceException`, and any non-null email is accepted without an `@` check. | `return customer.Email?.Contains('@') == true;` |
| 3 | `src/Orders/ReceiptService.cs:15` | high | `async void SendReceipt` makes exceptions from `SendAsync` unobservable, so they crash the process and the caller cannot await or handle them. | Change the signature to `public async Task SendReceiptAsync(...)` and await the call. |
| 4 | `src/Orders/OrderService.cs:30` | medium | `GetPage` is documented as 1-based but calls `Skip(page * pageSize)`, so page 1 skips a full page and returns the wrong items. Large values can also overflow. | `orders.Skip((page - 1) * pageSize).Take(pageSize).ToList()` |
| 5 | `src/Orders/ReceiptService.cs:24` | medium | `audit.WriteAsync` is not awaited, so audit failures are lost and `CompleteAsync` returns before the write finishes. The `ct` token is passed but never observed. | `await audit.WriteAsync($"Order {order.Id} completed", ct);` |
| 6 | `src/Orders/ReceiptService.cs:37` | medium | A new `HttpClient` is created on every call, which exhausts sockets under load. If `url` comes from untrusted input, the method is also an SSRF vector. | Use a shared injected `HttpClient` or `IHttpClientFactory`, and validate `url` against an allow-list if it can be user-controlled. |

Five clean hits and no noise. Row 6 is the “partial” in my table. It flags the right line, but for socket exhaustion, and misses that the request can’t succeed at all. Its fix (an injected client) happens to remove the bug anyway. The other three runs named it directly. From the first plain run:

| `src/Orders/ReceiptService.cs` | 37–38 | high | `using var client` is disposed when the method returns, before the request finishes. A new `HttpClient` per call also causes socket exhaustion and has no timeout. | Make the method `async` and `await` the call, or use a shared client from `IHttpClientFactory`. |

Haiku found the paging bug in every run, from the XML comment alone. That’s the one bug in this test where an LLM beat every analyzer. None of the runs complained about the GetTotal refactor. Run 2 called it “behavior-preserving”.

False Positives and Extras

Without the “bugs only” line, the plain runs added 4 and 6 extra rows, and the agentic run added 8. Most were fair points that I didn’t plant: CancellationToken.None, a hard-coded ops address, the culture-dependent {total:C}, no page validation, SSRF if url comes from users. One was wrong. From run 2:

| 17 | low | `order.Customer` may be null, which would throw here. | Confirm the nullability of `Order.Customer`; if it is nullable, check it before dereferencing. |

Customer is a required, non-nullable property, but Order.cs isn’t in the diff, so the model couldn’t see that. It said so and hedged. The agentic run had the tools to read it and didn’t make this mistake. Run 2 also put two findings one line off (23 and 29 instead of 24 and 30). Line numbers from a diff-only review are good enough for a human to read, but I wouldn’t post them as inline PR comments without checking.

Runs and Cost

run           model              turns  seconds  out tokens   cost USD
r1-plain      claude-haiku-5-5       1     27.4       5,103     0.0035
r2-plain      claude-haiku-5-5       1     19.5       3,409     0.0019
r3-bugs-only  claude-haiku-5-5       1     21.8       4,033     0.0025
r4-agentic    claude-haiku-5-5       4     29.6       3,472     0.0038
total                                                           0.0118

The cost column is total_cost_usd from the CLI’s JSON output. That’s four runs, about 20–30 seconds each, under half a cent per review for an 84-line diff. Bigger diffs cost more, and the agentic run reads files, so its input grows with the repo. It used 44,681 input tokens here, against about 5,500 for the diff-only runs. I didn’t try a larger model. The point was to see what the smallest one catches.

A Practical Setup

The two reviewers fail in different ways, so I’d use both, with different jobs.

1. Analyzers as a hard gate. Don’t turn every latest-all warning into an error. Pick the rules that find bugs and raise only those. In the test repo, a Directory.Build.props adds the two packages and a global config:

<ItemGroup Condition="'$(ExtraAnalyzers)' == 'true'">
  <PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="18.12.1" PrivateAssets="all" />
  <PackageReference Include="IDisposableAnalyzers" Version="4.0.8" PrivateAssets="all" />
</ItemGroup>
<!-- CI gate: -p:CiRules=true turns the bug-finding rules into errors -->
<ItemGroup Condition="'$(CiRules)' == 'true'">
  <GlobalAnalyzerConfigFiles Include="$(MSBuildThisFileDirectory)ci.globalconfig" />
</ItemGroup>
is_global = true

dotnet_diagnostic.CS4014.severity = error
dotnet_diagnostic.CS8602.severity = error
dotnet_diagnostic.CA2100.severity = error
dotnet_diagnostic.VSTHRD100.severity = error
dotnet_diagnostic.IDISP013.severity = error

(The two properties are only there so I could compare the builds. In a real project, reference the packages and the config unconditionally.) On the PR branch the gate fails with exactly the five bugs it can see:

OrderService.cs(24,9): error CA2100: Review if the query string passed to 'string DbCommand.CommandText' in 'CountBySkuAsync', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)
ReceiptService.cs(15,23): error VSTHRD100: Avoid "async void" methods, because any exceptions not handled by the method will crash the process (https://microsoft.github.io/vs-threading/analyzers/VSTHRD100.html)
ReceiptService.cs(24,9): error CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
ReceiptService.cs(30,39): error CS8602: Dereference of a possibly null reference.
ReceiptService.cs(38,16): error IDISP013: Await in using (https://github.com/DotNetAnalyzers/IDisposableAnalyzers/blob/master/documentation/IDISP013.md)
dotnet build exit code: 1

On main the same build exits with 0. The other 19 warnings stay warnings. This part is deterministic, free and takes seconds, so it can block a merge. If you don’t have a pipeline yet, start with GitHub Actions CI/CD for .NET.

2. The AI review as a comment, not a gate. It found the one bug no rule could, but its output changes between runs (4, 6 or 8 extras), and once it was wrong. Use the “bugs only” prompt if you want short reviews. Use the plain one if you’d rather see more and skip the noise yourself. Here’s the same setup as a GitHub Actions workflow. I didn’t run this in Actions. The commands are the ones I ran locally, but the workflow itself is untested. The AI job needs an Anthropic API key as a secret:

name: pr-review
on:
  pull_request:
    paths: ['**/*.cs']
permissions:
  contents: read
jobs:
  analyzers:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'
      - name: Build with the bug-finding rules as errors
        run: dotnet build src/Orders -p:AnalysisLevel=latest-all -p:ExtraAnalyzers=true -p:CiRules=true
  ai-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - run: npm install -g @anthropic-ai/claude-code
      - name: Review the diff with Claude Haiku
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          git diff origin/${{ github.base_ref }}...HEAD -- '*.cs' > pr.diff
          claude -p "$(cat prompts/bugs-only.txt)" --model haiku --tools "" --output-format json --max-budget-usd 0.50 < pr.diff > review.json
          jq -r .result review.json >> "$GITHUB_STEP_SUMMARY"

Two choices in there matter. --tools "" means the model only reads the diff and can’t run anything, so a review can’t run code from the PR. --max-budget-usd caps the spend of a single run. The review lands in the job summary, and a human decides what to do with it. For what a human reviewer should still check, I keep a C# code review checklist. For using Claude Code beyond reviews, see Claude Code for C# and .NET.

So Which AI Code Verification Tools Should a C# Team Use?

  • Always: nullable reference types and the compiler warnings. CS4014 and CS8602 found two of six bugs at zero cost. Don’t let a build hide them.
  • Cheap and deterministic: AnalysisLevel latest-all plus Microsoft.VisualStudio.Threading.Analyzers and IDisposableAnalyzers, with only the rules you trust raised to errors. Five of six here. For the SQL rule in depth, see SQL injection prevention in C#.
  • An LLM review on top for logic that matches no rule: comments that contradict the code, wrong boundaries, intent. The smallest Claude model was enough for this PR. Treat its output as a review comment, not a verdict.

What I Didn’t Test

  • Other AI reviewers. I didn’t test GitHub Copilot code review, CodeRabbit or other hosted tools, or larger Claude models. This is one small model through one CLI.
  • A real codebase. The PR is 84 lines with bugs I planted myself. A 2,000-line PR or bugs spread across files will score differently, and the planted bugs are the classic ones a model has seen many times.
  • Repeatability at scale. Four runs show the output varies. They don’t give a rate.
  • The GitHub Actions workflow. Written from the commands I ran locally, not run in Actions.
  • Commercial analyzers such as SonarQube or ReSharper inspections.

Related: Claude Code headless mode (docs) · CA2100 (Learn) · Claude Code for C# and .NET

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *