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.
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.
"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 onEnforceExtendedAnalyzerRulesso 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, ausingalias orvarwould beat it. I register a symbol action for properties, fields and parameters, look at the symbol's type, and if itsSpecialTypeisSystem_DoubleorSystem_Singleand the name ends in Amount, Price, Total or Gst, I reportACME0001on 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 withOutputItemType="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 areIDErules 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."
| 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) |
| 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 |
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.
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
DiagnosticDescriptor, Initialize with concurrency and generated-code settingsRed flags
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.
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.
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).AnalyzerReleases.Shipped.md / Unshipped.md for release tracking (RS2008).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.
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.
| 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 |
using Money = System.Double; alias and confirm the symbol-based check still reports it.-p:ReportAnalyzer=true in a solution of [100+] files.CodeFixProvider that changes the type to decimal and test it with the code-fix verifier.DateTime.Now rule with BannedApiAnalyzers and compare the effort.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>
double in syntax. Why it is wrong: misses System.Double, aliases and var. Instead: use the semantic model and SpecialType.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.CompilationStartAction.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.BannedSymbols.txt.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.