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

📚 Interview question

Your team keeps breaking a rule: money values must be decimal, never double. Write a small custom Roslyn analyser that enforces it, with a test. How do you package it for the team, and when would a banned-API list or an existing analyser be the better choice?

Covers writing a custom Roslyn DiagnosticAnalyzer for a team rule (money must be decimal), the project setup (netstandard2.0, EnforceExtendedAnalyzerRules), symbol actions, testing with Microsoft.CodeAnalysis.Testing, shipping via project reference or NuGet, performance rules, and when BannedApiAnalyzers or existing rules are better.

Mid-Level Coding Intermediate code-quality csharp custom-analyzer roslyn-analyzers static-analysis unit-testing

🎯 Key points

  • Analyser project targets netstandard2.0 (Visual Studio loads analysers on .NET Framework) and references Microsoft.CodeAnalysis.CSharp; set EnforceExtendedAnalyzerRules and IsRoslynComponent
  • DiagnosticAnalyzer with a DiagnosticDescriptor (id like ACME0001, category, default severity, help link to the ADR)
  • Initialize: EnableConcurrentExecution and ConfigureGeneratedCodeAnalysis(None); measure cost with -p:ReportAnalyzer=true
  • Use the semantic model: RegisterSymbolAction on properties, fields and parameters and check ITypeSymbol.SpecialType, not the text 'double'
  • Test with Microsoft.CodeAnalysis.CSharp.Analyzer.Testing: markup {|ACME0001:Total|} for expected diagnostics, plus a negative case
  • Ship as a ProjectReference with OutputItemType=Analyzer, or a versioned NuGet package (analyzers/dotnet/cs); pin Microsoft.CodeAnalysis to the oldest compiler the team uses
  • Agree the rule with the team first; prefer BannedApiAnalyzers or existing CA/IDE rules, because a custom analyser is code you must maintain

⏱ 30-second answer

A custom analyser is a class deriving from DiagnosticAnalyzer in a netstandard2.0 project that references Microsoft.CodeAnalysis.CSharp. I declare a DiagnosticDescriptor (ACME0001, category, severity, help link), and in Initialize call EnableConcurrentExecution(), skip generated code, and RegisterSymbolAction for properties, fields and parameters. The callback checks the symbol's type (SpecialType.System_Double) and the name (*Amount, *Price, *Total) and reports a diagnostic.

I test it with Microsoft.CodeAnalysis.CSharp.Analyzer.Testing, using markup like {|ACME0001:Total|}, and ship it as a project reference with OutputItemType="Analyzer" or a NuGet package, with severity in .editorconfig.

Trade-off: a custom analyser is code you maintain against Roslyn versions. If the rule is just 'never call X', BannedApiAnalyzers does it with a text file.

🗣 Full answer (senior)

How I would answer this in an interview

"A Roslyn analyser is just a class the compiler loads and calls back while it builds the semantic model. I'd create a separate project targeting netstandard2.0, because analysers have to load into Visual Studio, Rider and the command-line compiler, and reference Microsoft.CodeAnalysis.CSharp. I'd turn on EnforceExtendedAnalyzerRules so the Roslyn meta-analysers warn me if I do something unsafe, like keeping state between callbacks.

For this rule I don't want to search for the text 'double', because System.Double, a using alias or var would beat it. I register a symbol action for properties, fields and parameters, look at the symbol's type, and if its SpecialType is System_Double or System_Single and the name ends in Amount, Price, Total or Gst, I report ACME0001 on the identifier. I enable concurrent execution and skip generated code, because analysers run on every keystroke in the IDE and a slow one makes everyone's editor lag. Then I write tests with the Roslyn testing library: one source string with markup showing where the diagnostic must appear, and one that must produce nothing. We ship it as a project reference with OutputItemType="Analyzer" inside the solution, or as an internal NuGet package if several repos need it, and the team sets it to error in .editorconfig.

The mistake I see is writing a custom analyser when one already exists. 'Never use DateTime.Now' is a one-line entry in BannedApiAnalyzers; a lot of style rules are IDE rules you just have to enable. I write a custom one only when the rule needs the semantic model in a way no existing rule covers, and when the team has agreed the rule, because a custom analyser is code someone has to maintain."


Choosing the mechanism

Rule Best tool
Never call DateTime.Now, Thread.Sleep, Console.WriteLine BannedApiAnalyzers (BannedSymbols.txt)
Naming, var, braces, file-scoped namespaces IDE rules + .editorconfig
Pass CancellationToken through Existing CA2016
Money must be decimal (type + naming convention) Custom analyser
Domain project must not reference EF Core Architecture tests (NetArchTest, ArchUnitNET)

Moving parts

Piece Purpose
DiagnosticDescriptor Id, title, message, category, default severity, help link
SupportedDiagnostics Which ids this analyser can report
Initialize(AnalysisContext) Register callbacks; concurrency and generated-code options
SymbolAnalysisContext.ReportDiagnostic Emits the warning at a location
AnalyzerReleases.Unshipped.md Release tracking required by RS2008

Production example

After a rounding defect where a double discount produced invoices out by one cent on [0.4%] of orders, we added ACME0001 as an error. It flagged [23] existing members on day one, fixed in two PRs; the analyser added under [50 ms] to a [90-second] build, measured with -p:ReportAnalyzer=true.

🔍 What the interviewer is checking

Checks whether the candidate can turn a team rule into a correct, performant Roslyn analyser with tests, and has the judgement to prefer simpler mechanisms when they suffice.

Green flags

  • netstandard2.0, DiagnosticDescriptor, Initialize with concurrency and generated-code settings
  • Uses symbols/semantic model rather than text matching
  • Tests with the Roslyn testing library, including a negative case
  • Knows how to ship it (Analyzer project reference or NuGet) and set severity
  • Suggests BannedApiAnalyzers or existing rules where they fit

Red flags

  • Proposes a regex in a pipeline script
  • No tests or no idea how to test an analyser
  • Ignores IDE performance

📚 Learn in depth

1. How the compiler drives an analyser

Compilation starts
   │  loads analyser assemblies (netstandard2.0) from the 'Analyzer' items
   ▼
Initialize(context)  ── registers callbacks once per analyser instance
   │
   ├─ SyntaxNodeAction   (per node of a kind: fast, no types)
   ├─ SymbolAction       (per declared symbol: property, field, method, named type)
   ├─ OperationAction    (per IOperation: invocation, assignment: language-neutral)
   └─ CompilationStart   (per compilation: look up well-known types once)
   ▼
ReportDiagnostic(...) ──► severity from .editorconfig overrides default ──► IDE / build output

Callbacks can run in parallel and in any order, so an analyser must be stateless between callbacks, or keep state only inside a CompilationStartAction scope.

2. Syntax versus semantics

Syntax tells you the text was double; semantics tells you the type is System.Double. Aliases (using Money = System.Double;), var and generic substitutions only show up correctly in the semantic model. Symbol actions give you an ISymbol with a resolved ITypeSymbol, so SpecialType comparisons are both correct and cheap.

3. Project setup rules

  • Target netstandard2.0: the analyser loads into Visual Studio (.NET Framework host) as well as the .NET SDK compiler.
  • Reference Microsoft.CodeAnalysis.CSharp with PrivateAssets="all" and a version no newer than the oldest compiler your team uses; an analyser built against a newer Roslyn fails to load with CS8032 on older SDKs.
  • EnforceExtendedAnalyzerRules enables the RS1xxx meta-analysers (e.g. banned APIs inside analysers such as file I/O).
  • Add AnalyzerReleases.Shipped.md / Unshipped.md for release tracking (RS2008).

4. Code fixes

A CodeFixProvider (in a separate assembly that can reference Workspaces) can offer 'Change type to decimal'. Fixes run only in the IDE or dotnet format, never in the build, and must be tested with the code-fix verifier. Keep them optional: a correct analyser is worth more than a clever fix.

5. Performance

The IDE runs analysers on every edit. Measure with dotnet build -p:ReportAnalyzer=true -bl and look at the analyser timing in the binary log. Rules of thumb: register the narrowest action, resolve well-known types once per compilation, avoid SemanticModel calls in syntax actions when a symbol action would do, and skip generated code.

6. Distribution

Option When
ProjectReference with OutputItemType="Analyzer" ReferenceOutputAssembly="false" Rule used inside one solution
NuGet package, dll in analyzers/dotnet/cs/, DevelopmentDependency=true Shared across repositories, versioned
Directory.Build.props adds the package everywhere Organisation-wide rule

Try it yourself

  1. Build the analyser below, reference it from a sample project and see the squiggle appear in your IDE.
  2. Add a test for a using Money = System.Double; alias and confirm the symbol-based check still reports it.
  3. Write the same rule as a syntax-only analyser and find a case it misses.
  4. Measure analyser time with -p:ReportAnalyzer=true in a solution of [100+] files.
  5. Implement a CodeFixProvider that changes the type to decimal and test it with the code-fix verifier.
  6. Replace a DateTime.Now rule with BannedApiAnalyzers and compare the effort.

💻 Code

The analyser project and the rule (netstandard2.0 is still the required target for analysers, so no records; collection expressions and file-scoped namespaces are fine with LangVersion latest, but classic initialisers are used here for clarity).

<!-- Acme.Analyzers/Acme.Analyzers.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>latest</LangVersion>
    <Nullable>enable</Nullable>
    <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
    <IsRoslynComponent>true</IsRoslynComponent>
  </PropertyGroup>
  <ItemGroup>
    <!-- Deliberately not the newest: no newer than the oldest compiler (SDK / IDE) the team builds with -->
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" PrivateAssets="all" />
  </ItemGroup>
</Project>
// Acme.Analyzers/MoneyMustBeDecimalAnalyzer.cs
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Acme.Analyzers;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class MoneyMustBeDecimalAnalyzer : DiagnosticAnalyzer
{
    public const string Id = "ACME0001";
    private static readonly string[] MoneySuffixes = new[] { "Amount", "Price", "Total", "Gst" };

    private static readonly DiagnosticDescriptor Rule = new(
        id: Id,
        title: "Money must be decimal",
        messageFormat: "'{0}' looks like money but is '{1}'; use decimal to avoid binary rounding errors",
        category: "Reliability",
        defaultSeverity: DiagnosticSeverity.Warning,
        isEnabledByDefault: true,
        helpLinkUri: "https://wiki.example.internal/adr/0017-money-is-decimal");

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context)
    {
        context.EnableConcurrentExecution();                                    // runs on every keystroke
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); // skip generated files
        context.RegisterSymbolAction(Analyse, SymbolKind.Property, SymbolKind.Field, SymbolKind.Parameter);
    }

    private static void Analyse(SymbolAnalysisContext ctx)
    {
        ITypeSymbol? type = ctx.Symbol switch
        {
            IPropertySymbol p => p.Type,
            IFieldSymbol f => f.Type,
            IParameterSymbol p => p.Type,
            _ => null
        };
        // Unwrap double? so nullable money is caught too.
        if (type is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } n)
            type = n.TypeArguments[0];
        // Semantic check: catches System.Double and using-aliases, not just the keyword.
        if (type is null || (type.SpecialType != SpecialType.System_Double && type.SpecialType != SpecialType.System_Single))
            return;
        var name = ctx.Symbol.Name;
        if (!MoneySuffixes.Any(s => name.EndsWith(s, StringComparison.OrdinalIgnoreCase)))
            return;

        foreach (var location in ctx.Symbol.Locations)
            ctx.ReportDiagnostic(Diagnostic.Create(Rule, location, name, type.ToDisplayString()));
    }
}
// Acme.Analyzers.Tests/MoneyMustBeDecimalAnalyzerTests.cs (xUnit + Microsoft.CodeAnalysis.CSharp.Analyzer.Testing)
using Verify = Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerVerifier<
    Acme.Analyzers.MoneyMustBeDecimalAnalyzer, Microsoft.CodeAnalysis.Testing.DefaultVerifier>;

namespace Acme.Analyzers.Tests;

public class MoneyMustBeDecimalAnalyzerTests
{
    [Fact]
    public Task Flags_double_and_float_money_members() => Verify.VerifyAnalyzerAsync("""
        using Money = System.Double;

        public class Invoice
        {
            public double {|ACME0001:TotalAmount|} { get; set; }
            private float {|ACME0001:_unitPrice|};
            public Money {|ACME0001:Gst|} { get; set; }
            public void ApplyDiscount(double? {|ACME0001:discountAmount|}) { }
        }
        """);

    [Fact]
    public Task Ignores_decimal_and_non_money_doubles() => Verify.VerifyAnalyzerAsync("""
        public class Invoice
        {
            public decimal TotalAmount { get; set; }
            public double DistanceKm { get; set; }   // not money: no diagnostic
        }
        """);
}
<!-- Consumer: Billing.Domain.csproj, plus severity in .editorconfig: dotnet_diagnostic.ACME0001.severity = error -->
<ItemGroup>
  <ProjectReference Include="..\Acme.Analyzers\Acme.Analyzers.csproj"
                    OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

⚠ Common mistakes

  • Mistake: Matching the text double in syntax. Why it is wrong: misses System.Double, aliases and var. Instead: use the semantic model and SpecialType.
  • Mistake: Targeting net10.0 for the analyser project. Why it is wrong: Visual Studio and older hosts can't load it. Instead: target netstandard2.0.
  • Mistake: Referencing the newest Microsoft.CodeAnalysis.CSharp. Why it is wrong: teammates on an older SDK get CS8032 and the analyser silently doesn't run. Instead: pin to the oldest supported compiler version.
  • Mistake: Keeping mutable static state across callbacks. Why it is wrong: callbacks run concurrently and per compilation; results become random. Instead: stay stateless or scope state in CompilationStartAction.
  • Mistake: Forgetting EnableConcurrentExecution and generated-code settings. Why it is wrong: slows every build and keystroke, and reports on code nobody can edit. Instead: set both in Initialize.
  • Mistake: Only testing the positive case. Why it is wrong: false positives are what make teams disable rules. Instead: add negative tests for near-misses.
  • Mistake: Writing a custom analyser for a banned API. Why it is wrong: more code to maintain. Instead: BannedApiAnalyzers with BannedSymbols.txt.

🏛 Senior insight: trade-offs

A custom analyser turns a team agreement into something the compiler enforces, which is far more reliable than a wiki page or a review checklist. But it is production code: it needs tests, versioning, an owner and a help link that explains the rule (ideally the ADR). I'd only write one after checking the SDK rules, BannedApiAnalyzers and popular packs, and after the rule has been agreed, because an analyser that people resent gets suppressed.

Option When it fits Cost When not to
Existing CA/IDE/third-party rule Rule already exists Configuration only Never skip checking
BannedApiAnalyzers 'Never call this API' A text file Rules that depend on context or types of declarations
Architecture tests Layering and dependency rules Test project Per-line coding rules
Custom analyser Type- or context-aware rule unique to your domain Code, tests, Roslyn version care Rule not agreed, or rarely broken

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions testing and shipping the analyser Why: Checks depth on testing, packaging and versioning analysers
    How to answer

    An analyser is a class deriving from DiagnosticAnalyzer with [DiagnosticAnalyzer(LanguageNames.CSharp)]. It declares DiagnosticDescriptors (id, title, message, category, default severity) and in Initialize calls EnableConcurrentExecution(), ConfigureGeneratedCodeAnalysis(...) and registers callbacks such as RegisterSymbolAction, RegisterSyntaxNodeAction or RegisterOperationAction, reporting with context.ReportDiagnostic. It targets netstandard2.0 like a generator. Test it with Microsoft.CodeAnalysis.CSharp.Analyzer.Testing using markup such as {|DEMO001:Run|}. Ship it as a project reference with OutputItemType="Analyzer" or a NuGet package, and let teams tune severity in .editorconfig.

  2. When: Candidate mentions setting severity in .editorconfig Why: Checks how analyser configuration works across a team
    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.

  3. When: Candidate mentions the Microsoft.CodeAnalysis package version Why: Checks understanding of analyser loading and compiler version compatibility
    How to answer

    The analyser was compiled against a newer Microsoft.CodeAnalysis than the Roslyn compiler in the older SDK or IDE. The host can't load it, reports CS8032 ('an instance of analyser cannot be created') in the build output, and then silently skips it, so in the IDE it simply looks like the rule never fires. Fix: pin the Microsoft.CodeAnalysis.CSharp reference to the oldest compiler version the team supports, pin the SDK for everyone with global.json, check that IDE versions match, and add a CI test that a known-bad sample actually produces the diagnostic, so a non-loading analyser fails the build instead of passing quietly.

🛠 Real-world problems: how you handle them

One-cent invoice errors traced to double money fields
Situation
An [order and invoicing] service handling [40k] invoices a day; customers reported invoices out by one cent, and finance found [0.4%] of invoices failing reconciliation.
Signals
Reconciliation job mismatches of exactly 0.01; support tickets about GST lines; no failing unit tests.
Investigation
Reproduced with a failing test on a discounted line; found `double DiscountAmount` multiplied and rounded with `Math.Round` (banker's rounding on binary values); searched the codebase and found [23] other money members typed `double` or `float`, introduced by several developers despite a wiki rule.
Resolution
Immediately: changed the discount path to `decimal` with `MidpointRounding.AwayFromZero` and re-issued affected invoices. Then: wrote `ACME0001`, fixed all [23] members in two PRs, made the rule an error in `.editorconfig`.
Prevention
Analyser tests in CI; ADR 'money is decimal' linked from the diagnostic help link; analyser included via `Directory.Build.props` in all billing projects; reconciliation mismatch alert in Application Insights.

How to tell it (STAR)

**S:** At [company] our invoicing service produced invoices out by a cent on about [0.4%] of orders. **T:** I had to fix the defect and stop it coming back, because the 'use decimal' rule was only on a wiki. **A:** I traced it to `double` discount fields, fixed the rounding, then wrote a small Roslyn analyser that flags money-named members of type double or float, with tests, and made it an error for all billing projects. **R:** It found [23] more cases on day one; after the fix reconciliation mismatches dropped to [zero], and the rule has blocked [several] PRs since without anyone needing to spot it in review.

More in Static Analysis

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me