Covers what static analysis is, the kinds of defects it finds that tests miss, and the main .NET tools (compiler and nullable warnings, .NET SDK CA/IDE analysers, StyleCop, SonarAnalyzer, Roslynator, BannedApiAnalyzers, CodeQL) and where they run.
Static analysis examines code without running it. In .NET most of it is done by Roslyn analysers that run inside the compiler, so the same warning shows up as a squiggle in the IDE, in dotnet build and in the CI pipeline.
Tests only check the paths you thought to exercise; an analyser checks every path for a known bad pattern: a possible null dereference (CS8602), an IDisposable that is never disposed (CA2000), async void, culture-sensitive decimal.Parse (CA1305), or SQL concatenated from user input (CA2100).
CA/IDE rules, configured in .editorconfig.The trade-off: analysers are cheap and thorough for patterns, but they cannot tell you the business logic is right, and noisy rules get ignored.
"Static analysis means checking code for problems without executing it. In .NET the main engine is Roslyn: analysers are plugged into the compiler, so they see the same syntax trees and semantic model the compiler builds. That's why a warning like
CA2000, 'dispose objects before losing scope', appears as a squiggle while I type, failsdotnet buildif we've made it an error, and fails the pull request build in exactly the same way.What it catches that tests don't is every path. My unit tests prove the order total is right for the cases I wrote. An analyser looks at all 400 methods and says: here you parse a decimal with the current culture, here you can dereference null, here an
HttpResponseMessageis never disposed, here someone built SQL with string concatenation. Those bugs often live in the error path or the rarely used branch that no test reaches. The tools I'd name are the compiler and nullable warnings, theCAandIDErules that ship in the .NET SDK, configured through.editorconfig; then packages like StyleCop.Analyzers for layout and documentation rules, SonarAnalyzer or Roslynator for extra quality rules, and BannedApiAnalyzers to forbid specific APIs. On top of the build there are platforms such as SonarQube and GitHub CodeQL that track issues over time and run deeper security data-flow analysis.The mistake I see is treating analysers as a replacement for tests, or turning on every rule at once and drowning the team in 3,000 warnings that everyone learns to ignore. Static analysis tells you the code is built well; tests tell you it does the right thing. You need both, and you need the warning list kept short enough that a new warning is noticed."
| Defect | Unit tests | Static analysis |
|---|---|---|
| Wrong GST calculation | Yes, if you wrote the case | No |
| Null dereference in a rare error path | Only if a test hits that path | Yes (CS8602, CS8604) |
HttpClient created per call, undisposed stream |
Rarely | Yes (CA2000, CA1816) |
| SQL built from user input | Only with a security test | Yes (CA2100, Sonar S3649, CodeQL) |
async void event handler swallowing exceptions |
Rarely | Yes (VSTHRD100, Sonar S3168) |
| Inconsistent naming, file layout | No | Yes (IDE1006, StyleCop SA rules) |
| Race condition under load | Rarely | Mostly no |
| Tool | What it is | Where it runs |
|---|---|---|
Compiler warnings incl. nullable (CS86xx) |
Part of Roslyn | IDE, build, CI |
.NET SDK analysers (CA quality, IDE style) |
Ship with the SDK, EnableNETAnalyzers is on by default |
IDE, build (IDE rules need EnforceCodeStyleInBuild) |
.editorconfig |
Not a tool: the shared settings file for rule severity and style | Read by IDE and compiler |
| StyleCop.Analyzers | NuGet analyser pack for layout, ordering, documentation (SA rules); still published on NuGet as of November 2026 |
IDE, build |
| SonarAnalyzer.CSharp, Roslynator, Meziantou.Analyzer | Extra quality and bug rules | IDE, build |
| Microsoft.CodeAnalysis.BannedApiAnalyzers | Fails the build if a listed API (e.g. DateTime.Now) is used |
IDE, build |
| SonarQube Server / SonarQube Cloud | Platform: issue history, quality gates, PR decoration | CI |
| GitHub CodeQL | Semantic security queries with taint tracking | CI |
dotnet format |
Applies fixes for style and analyser rules | Local, CI check |
On a team of eight, turning CA2000 and CA2213 into errors for an order service flagged 14 undisposed SqlCommand and stream objects; two of them were the cause of a slow connection-pool leak that only showed after about six hours of traffic. No test had failed, because each test ran for milliseconds.
Checks that the candidate understands what static analysis is for, how it differs from testing, and can name the real .NET tools and where they run.
Green flags
CS8602, CA2000, CA1305).editorconfig as the shared place for severityRed flags
The C# compiler parses source into syntax trees, binds names to symbols to build a semantic model, and then emits IL. An analyser is a class deriving from DiagnosticAnalyzer that registers callbacks on that pipeline:
source .cs ─► parse ─► SyntaxTree ─► bind ─► SemanticModel / IOperation ─► emit IL
│ │
RegisterSyntaxNodeAction RegisterOperationAction
└───────── analyser ─────┘
│
Diagnostic (id, severity, location)
Because the analyser runs in the compiler process, the IDE (live analysis), dotnet build and CI all report the same diagnostic ids. That consistency is the main reason Roslyn analysers replaced older post-build tools such as FxCop binaries.
| Kind | Example | Cost |
|---|---|---|
| Syntactic / style | Braces, naming, var usage |
Very cheap |
| Semantic pattern | Calling string.Format without a culture, Task.Result |
Cheap |
| Flow analysis | Nullable state: is this variable maybe-null here? | Moderate |
| Taint / data flow across methods | User input reaches a SQL command | Expensive, usually CodeQL or Sonar in CI |
The nullable checker is flow analysis built into the compiler: it tracks whether each reference is not-null or maybe-null along every branch, which is exactly what tests struggle to do.
EnableNETAnalyzers is true by default for projects targeting .NET 5 and later.AnalysisLevel chooses which version of the rule set you get, and AnalysisMode (None, Default, Minimum, Recommended, All) chooses how many are enabled as warnings. You can combine them, for example <AnalysisLevel>latest-recommended</AnalysisLevel>. Pin it explicitly so an SDK upgrade doesn't silently change the bar.IDE style rules only run in the build with <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>..editorconfig: dotnet_diagnostic.CA1305.severity = warning.An analyser judges patterns, not intent, so it will sometimes be wrong. Suppress at the narrowest scope with a reason: [SuppressMessage("Reliability", "CA2000", Justification = "Ownership passes to the caller")], rather than turning the rule off for the whole solution.
It cannot know your business rules, it struggles with reflection and dynamic code, and cross-service behaviour (a message queue, a database trigger) is invisible to it. Treat it as one safety net next to tests, code review and runtime monitoring.
decimal.Parse("1,5") and an unused new MemoryStream(). Build with <AnalysisMode>All</AnalysisMode> and note which CA rules fire.<Nullable>enable</Nullable> on an old class and count the CS86xx warnings; fix three and see how the method signatures change..editorconfig that raises CA2000 to error and confirm both the IDE and dotnet build fail.dotnet format analyzers --severity warn --verify-no-changes and read its output.stylecop.json.A typical before/after: the analysers flag real problems in an invoice parser that all its unit tests passed.
// Before: compiles, tests pass on an en-AU build agent.
namespace Billing;
public class InvoiceImporter
{
public decimal ReadTotal(string path)
{
var reader = new StreamReader(path); // CA2000: never disposed
var line = reader.ReadLine(); // may be null
var parts = line.Split(','); // CS8602: possible null dereference
return decimal.Parse(parts[1]); // CA1305: uses current culture
}
}
// After: every warning fixed, behaviour is the same on any culture.
using System.Globalization;
namespace Billing;
public sealed class InvoiceImporter
{
public async Task<decimal> ReadTotalAsync(string path, CancellationToken ct)
{
using var reader = new StreamReader(path); // disposed on every path
var line = await reader.ReadLineAsync(ct)
?? throw new InvalidDataException($"Invoice file '{path}' is empty.");
var parts = line.Split(',');
// Invariant culture: the file format is fixed, not the user's locale.
return decimal.Parse(parts[1], NumberStyles.Number, CultureInfo.InvariantCulture);
}
}
# .editorconfig (repository root): one place for the team's rule severities
root = true
[*.cs]
dotnet_diagnostic.CA2000.severity = error
dotnet_diagnostic.CA1305.severity = warning
dotnet_diagnostic.CS8602.severity = error
AnalysisMode All in an old solution on day one. Why it is wrong: thousands of warnings teach the team to ignore warnings. Instead: start with Recommended, fix or baseline, then tighten.Justification..editorconfig and Directory.Build.props.IDE style rules to fail the build by default. Why it is wrong: they need EnforceCodeStyleInBuild. Instead: set it and check with dotnet build.Even at junior level, the useful mindset is that analysers are cheap reviewers that never get tired: they should catch the mechanical issues so human reviewers can spend their attention on design and behaviour. The value depends entirely on signal-to-noise. A short list of rules the team agrees with, enforced as errors in CI, beats hundreds of rules at warning level that nobody reads.
Where it sits in the pipeline. Fast Roslyn rules run on every local build and in the PR build, so feedback arrives in minutes. Heavier tools (SonarQube, CodeQL taint analysis) run in CI on the PR and nightly, because they can add several minutes. Each analyser package adds compile time; on large solutions measure it with dotnet build -bl and the Analyzer Summary in the MSBuild Structured Log Viewer (or -p:ReportAnalyzer=true) before adding another pack. Older non-SDK-style (.csproj with packages.config) projects don't get the SDK analysers automatically; add the Microsoft.CodeAnalysis.NetAnalyzers package.
When there are already hundreds of warnings, don't try to fix them all: agree a small set of rules that matter (nullability, disposal, security), fix or suppress those, make them errors so the count can't grow, and widen the set over time. Agree the rules with the team in a short discussion rather than imposing them, or people reach for blanket suppressions.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SDK CA/IDE rules only |
Every project, start here | Free, already installed | Never skip |
| + StyleCop.Analyzers | Teams that want strict, uniform layout and XML docs | Many style warnings at first | Small teams happy with IDE style rules |
| + SonarAnalyzer / Roslynator | Want extra bug and smell rules in the IDE | Some overlap with CA rules, extra build time |
When the team can't yet handle the existing warnings |
| SonarQube / CodeQL in CI | Need history, quality gates, deep security analysis | Setup, licence or Actions minutes, slower pipeline | Tiny throwaway prototypes |
Analysers are plug-ins for the Roslyn compiler. They report diagnostics in the editor and during the build. CA rules (CA1xxx to CA5xxx) are the SDK's code quality analysers, covering design, performance, reliability and security. The .NET analysers are enabled by default for net5.0+ projects (EnableNETAnalyzers), but only a default subset of rules reports as warnings; AnalysisLevel and AnalysisMode set how many apply. IDE rules (IDE0xxx) are code style rules, such as var usage or file-scoped namespaces. They show in the editor but only run in the build when EnforceCodeStyleInBuild is true, which is why style issues often pass CI. Severities for both are set in .editorconfig (or a .globalconfig) with dotnet_diagnostic.<id>.severity. Third-party analysers come in as NuGet packages. For a team, I put the levels in Directory.Build.props, the severities in one root config file, and tighten them step by step.
<Nullable>enable</Nullable> makes reference types non-nullable by default: string? means a value can be null and string means it can't. The compiler then warns when code might dereference null. It's purely compile-time, so nothing changes at run time. In a big codebase I migrate bottom-up: shared libraries and domain types first, because their annotations flow out to everyone else. I go project by project, or file by file with #nullable enable, and give each step a small pull request so feature work carries on. When a project is clean I make its nullable warnings errors with WarningsAsErrors=nullable, so it can't slip back. I use attributes such as [NotNullWhen] where flow analysis needs help and keep ! for real boundaries. I also watch for two things: EF Core migrations, where nullability decides whether columns are required, and public APIs, where annotations are part of the contract.
Not across the board. First agree which rules matter, fix or suppress the existing hits, then make those rules errors (in .editorconfig or with WarningsAsErrors) so new code can't add them. Turning everything into errors at once blocks delivery and pushes people to blanket NoWarn. Once the count is zero, TreatWarningsAsErrors in CI keeps it there.
Last updated 23 Nov 2026.