📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is static analysis, and what does it catch that your unit tests don't? Name the main static analysis tools a .NET team uses and where each one runs.

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.

Junior Theory Beginner code-quality csharp editorconfig nullable-reference-types roslyn-analyzers static-analysis

🎯 Key points

  • Static analysis inspects source or IL without running it, so it checks every path, not only the paths tests execute
  • Catches whole classes of defect: possible null dereference (CS8602), undisposed IDisposable (CA2000), async void, culture-sensitive parsing (CA1305), SQL built from strings (CA2100)
  • Roslyn analysers run inside the compiler: same warnings in the IDE, in dotnet build and in the CI pipeline, so a PR build can fail on them
  • Built into the .NET SDK: EnableNETAnalyzers on by default for SDK-style projects targeting .NET 5+, tuned with AnalysisLevel / AnalysisMode; IDE style rules need EnforceCodeStyleInBuild
  • Severity is configured in .editorconfig (dotnet_diagnostic.CA2000.severity = error), shared across the team
  • Third-party packs: StyleCop.Analyzers (layout and docs), SonarAnalyzer.CSharp, Roslynator, Meziantou.Analyzer; platform tools: SonarQube, CodeQL
  • Analysers complement tests and code review: they cannot tell you the business rule is right, cost some build time, and produce false positives you must triage

⏱ 30-second answer

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).

  • Built in: compiler and nullable warnings, the .NET SDK CA/IDE rules, configured in .editorconfig.
  • Add-ons: StyleCop.Analyzers, SonarAnalyzer.CSharp, Roslynator, BannedApiAnalyzers.
  • Platforms: SonarQube / SonarQube Cloud, GitHub CodeQL.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, fails dotnet build if 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 HttpResponseMessage is 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, the CA and IDE rules 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."


What finds what

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

The main .NET tools

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains that analysers check all paths without executing code, with concrete rule examples (CS8602, CA2000, CA1305)
  • Knows Roslyn analysers give the same result in IDE, build and CI
  • Mentions .editorconfig as the shared place for severity
  • Says analysers complement tests, not replace them

Red flags

  • Thinks static analysis means 'linting for formatting' only
  • Can't name a single .NET analyser or rule
  • Believes analysers prove the code is correct or secure

📚 Learn in depth

1. Where Roslyn analysers sit

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.

2. Kinds of static analysis

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.

3. How the built-in rules are switched on

  • 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>.
  • Per-rule severity lives in .editorconfig: dotnet_diagnostic.CA1305.severity = warning.

4. False positives and suppression

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.

5. What static analysis cannot do

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.

Try it yourself

  1. Create a console app, write decimal.Parse("1,5") and an unused new MemoryStream(). Build with <AnalysisMode>All</AnalysisMode> and note which CA rules fire.
  2. Enable <Nullable>enable</Nullable> on an old class and count the CS86xx warnings; fix three and see how the method signatures change.
  3. Add an .editorconfig that raises CA2000 to error and confirm both the IDE and dotnet build fail.
  4. Run dotnet format analyzers --severity warn --verify-no-changes and read its output.
  5. Add StyleCop.Analyzers to a project and compare the number of warnings with and without a stylecop.json.

💻 Code

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

⚠ Common mistakes

  • Mistake: Believing high test coverage makes analysers unnecessary. Why it is wrong: coverage proves a line ran, not that every null or culture path is safe. Instead: use both; analysers find pattern bugs across all paths.
  • Mistake: Turning on 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.
  • Mistake: Disabling a rule solution-wide because of one false positive. Why it is wrong: you lose every true positive too. Instead: suppress at the member with a Justification.
  • Mistake: Configuring rules only in each developer's IDE settings. Why it is wrong: CI and teammates don't see them. Instead: commit an .editorconfig and Directory.Build.props.
  • Mistake: Expecting IDE style rules to fail the build by default. Why it is wrong: they need EnforceCodeStyleInBuild. Instead: set it and check with dotnet build.
  • Mistake: Treating static analysis as a security sign-off. Why it is wrong: it misses logic flaws, authorisation gaps and config mistakes. Instead: combine it with threat modelling, review and testing.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions CA and IDE rules or .editorconfig Why: Checks they know how analysers are configured across a team, not just that they exist
    How to answer

    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.

  2. When: Candidate mentions nullable warnings Why: Checks whether they can roll out nullable reference types in a real codebase
    How to answer

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

  3. When: Candidate says warnings should be fixed Why: Checks judgement about rolling out enforcement without stopping the team
    How to answer

    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.

More in Static Analysis

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me