The C# twin (or little sister) of FSharp.Refactor: functional refactoring suggestions for C#.
The same product as FSharp.Refactor, for C#:
- light-bulb quick fixes in the editor (VS Code, Visual Studio 2022/2026),
- a command-line tool that applies them in bulk, build-verified, with reports, a baseline ratchet and an MCP server for agents.
What the rules care about, in the same order as the F# side:
- Correctness — the code does something other than what it looks like it does: a race, a swallowed exception, a disposable that leaks, a task nobody observes, a comparison that never holds.
- Performance — correct, but doing work it need not: allocations that
need not happen, repeated work, a scan where a lookup would do. Every
performance claim is measured in
benchmarks/PerfClaims. - Idiom — the same behaviour written the way clear, functional C# writes
it: expressions over statements, patterns over casts, immutable records
over mutable bags, LINQ over flag loops,
awaitover.Result. Opinionated towards F# and functional programming, without pretending C# is F#. - Cosmetic — punctuation and spelling. Few, and mostly off by default,
because C# already has
dotnet formatand the IDE rules for that. We don't want to do rules that would contradict with dotnet format.
What it deliberately does NOT care about: naming, file layout, member
ordering, var versus explicit types, braces, this., method length,
cyclomatic complexity. Those are house style and other tools' business
(IDExxxx, StyleCop, SonarQube). Agent-generated code makes structure rules
matter less every year; what it does not make matter less is whether the
code is right and whether it does needless work.
Two things change when the language is C#, and they shape everything below:
- Roslyn is the host. C# already has a first-class analyzer and code-fix
pipeline, loaded by every editor and by the compiler itself. There is no
sidecar, no analyzer-SDK version pairing, no
analyzersPathsetting. The analyzers ship as an ordinary Roslyn analyzer NuGet package (analyzers/dotnet/cs) and light up in VS, VS Code (C# Dev Kit / C# extension), Rider anddotnet buildby reference alone. Both IDE plugins are therefore much thinner than their F# counterparts. - Microsoft already ships hundreds of C# rules (CAxxxx, IDExxxx, SYSLIBxxxx).
Many F# rules exist only because those never ran on F#. On C# we do not
duplicate a rule that has a fix and is on by default; we implement a rule
Microsoft has note-only or off by default, and under
csharp_refactor.skip_microsoft_duplicates = truewe stand down when the user has turned the Microsoft rule on. See §7.
Rule codes are CR0001… (CR is unused by Microsoft, StyleCop SA, Sonar
S, Roslynator RCS, Meziantou MA, CodeRush CRR). Codes are assigned in
order of introduction and never reused; the v1 set below is numbered by
family for readability, later rules append.
- Formatting. Fixes are minimal range-based text edits; the tool never runs
the Roslyn formatter over a file, and nothing it emits fights
dotnet formator.editorconfiglayout rules. - A second configuration system. Rules are configured the way every Roslyn
analyzer is:
.editorconfig. See §6. - Reimplementing Microsoft's fixes. Where CA/IDE has a fix and is on by default, the row in the overlap table says "defer".
- Rules that move code AWAY from idiomatic C#, or reversible matters of taste
(
switchstatement ↔ expression where both read fine, query ↔ method syntax, expression-bodied ↔ block-bodied). Those belong to Roslyn's user-invoked refactorings, not to a diagnostic. - Naming, structure, conventions. See §1 and §10.
| Piece | Package / id | What it is |
|---|---|---|
| Analyzers | CSharp.Refactor.Analyzers (NuGet, DevelopmentDependency) |
Roslyn DiagnosticAnalyzer + CodeFixProvider assembly, F#, netstandard2.0, with FSharp.Core.dll beside it in analyzers/dotnet/cs. Loads in csc, VS, VS Code, Rider, dotnet format. |
| Apply tool | csharp-refactor (dotnet tool) |
MSBuildWorkspace host: analyses a project/solution/directory/glob, applies non-overlapping fixes bottom-up, recompiles in memory per pass, builds at the end, reports (SARIF/HTML/CSV/JSON), ratchets (--baseline), serves MCP (--mcp). Same flag contract as fsharp-refactor. |
| VS Code | csharp-refactor-vscode |
Bundles the analyzer assembly; with consent wires it machine-wide (an MSBuild user ImportBefore props) or per project (PackageReference); commands to run the tool, write reports, review notes, create config. |
| Visual Studio 2022/2026 | CSharp.Refactor.vsix |
Ships the analyzer as a VSIX analyzer asset, so every C# project in the IDE gets the light bulbs with no project change and no build impact; a Tools menu drives the tool. No sidecar process. |
| MCP | csharp-refactor --mcp |
analyze (target, codes/categories, parseOnly, apply) and list_rules over stdio; the process and MSBuild stay warm, each call loads its target afresh. |
One version for all of them, in Directory.Build.props, released in lockstep.
Severity: every finding is Info (VS: "suggestion" dots + light bulb; not
in build output at normal verbosity; never gates a build). Priority rules are
Warning, as on the F# side. Every message ends with its category in
brackets, because editors truncate from the right. Cosmetic rules that
remove text also carry WellKnownDiagnosticTags.Unnecessary, so the
redundant text is faded rather than squiggled.
CSharp.Refactor/
Directory.Build.props one <Version> for the whole solution
CSharp.Refactor.slnx
README.md Rules.md CHANGELOG.md DESIGN.md (this file)
src/
CSharp.Refactor.Analyzers/ F#, netstandard2.0; one module per rule family; Analyzers.fs + CodeFixes.fs adapters
CSharp.Refactor.Tool/ F#, net10.0 (rolls forward); MSBuildWorkspace host, apply loop, reports, MCP
CSharp.Refactor.VsCode/ TypeScript extension
CSharp.Refactor.Vsix/ VSIX manifest + F# package for the Tools menu
tests/
CSharp.Refactor.Tests/ xunit; string-literal inputs, compile-verified fixes, Rules.md kept in step
Sample/ a C# project the sweep must leave clean (idempotency, from-scratch compare)
benchmarks/
PerfClaims/ BenchmarkDotNet; one before/after pair per performance claim
The analyzer assembly is F# because the rule logic is pattern matching over trees, which is F#'s home ground, and because the shared vocabulary with FSharp.Refactor (Suggestion, Fix, Scope, Visibility, Configuration, the purity proofs) ports as modules rather than as ideas. Constraints this imposes, all verified by the M0 spike:
netstandard2.0. Visual Studio's devenv process hosts Roslyn on .NET Framework, so a Roslyn analyzer must targetnetstandard2.0to load everywhere (csc underdotnet buildis .NET Core and would accept more; VS would not). FSharp.Core supports netstandard2.0; the analyzer uses no API above it.- Roslyn version pin. An analyzer compiles against ONE
Microsoft.CodeAnalysis.CSharpversion and loads in any host with that version or newer, binding at runtime to the host's copy. Pin the lowest version whose syntax model covers the C# we need to read. The pin is 4.14, so the hosts are VS 17.14+ and .NET SDK 9.0.300+; an older compiler warns CS9057 and loads no rule. The tool hosts its own newer Roslyn (5.x from the .NET 10 SDK) and loads the same analyzer assembly. Syntax kinds the pinned version does not name (C# 14field, extension members) arrive as nodes whose kind the rule code has no case for; every walker treats an unknown node as opaque, never as a match, and a test feeds a C# 14 file through every rule. - FSharp.Core beside the analyzer. The compiler's analyzer loader
resolves an analyzer's dependencies from its own directory, so
FSharp.Core.dllis packed intoanalyzers/dotnet/csnext to the analyzer (IncludeBuildOutput=false, explicitNone Packitems, as the F# package does). Risk: two F# analyzers in one compilation wanting different FSharp.Core versions; the loader keeps one per assembly name. Mitigation: a widely used FSharp.Core pin, and a test that loads the package throughcscrather than through the test host. - MEF export attributes from F#.
[<DiagnosticAnalyzer(LanguageNames.CSharp)>]on a class inheritingDiagnosticAnalyzer, and[<ExportCodeFixProvider(LanguageNames.CSharp, Name = "…")>] [<Shared>]on aCodeFixProvidersubclass. Plain CLR attributes; F# closures compile to nested classes MEF ignores. Verified in M0 in all three hosts. Microsoft.CodeAnalysis.Analyzers(RS1xxx) do not analyse F# source, so the analyzer-correctness checks a C# analyzer project gets for free are replaced by tests: every code in the catalog has a descriptor, every descriptor is inSupportedDiagnostics, every fixable code has a fix provider registered for it, every message ends in its category.
Identical to the F# side's third design principle. Each rule is a pure function
SyntaxTree -> SemanticModel option -> RuleContext -> Suggestion listwhere Suggestion carries the code, message, span, and zero or more Fixes,
each a list of (TextSpan * replacement) text changes plus an editor-only
flag and an equivalence key. Analyzers.fs turns suggestions into Roslyn
Diagnostics; CodeFixes.fs turns Fixes into CodeActions whose only
operation is document.WithText(text.WithChanges changes). No
SyntaxGenerator, no Formatter.Format, no ReplaceNode that re-serialises
trivia: the edited span is what changes, nothing else. The tool calls the
pure core directly and never depends on MEF.
One memoised walk per file version: the analyzer registers a single
SemanticModelAction (and a SyntaxTreeAction for the parse-only rules),
builds one indexed view of the tree (the AstIndex twin: nodes by kind, by
enclosing member, invocations by callee name), and every enabled rule reads
that. A disabled rule costs nothing. EnableConcurrentExecution is on;
ConfigureGeneratedCodeAnalysis(None) lets Roslyn skip generated files
(.g.cs, <auto-generated>, [GeneratedCode]) before we see them.
Deep trees: the F# analyzers run on 64 MB worker threads because
a + b + c + … nests one node per operand and a StackOverflowException
ends the host. Roslyn's own walkers use explicit stacks, but our recursive
rule functions do not; the DeepStack worker pool is kept.
Every rule declares whether it needs the semantic model. The parse-only
rules (--parse-only, and the editor before a project has loaded) run from
syntax alone; the typed rules never guess: a receiver whose type the model
cannot settle stands the rule down. Roslyn makes the typed gate cheaper than
FCS did — GetSymbolInfo, GetTypeInfo, GetOperation are per-node and
lazy — so the default is typed, and a rule is parse-only only when its shape
is decidable from syntax alone (attribute suffix, $"no holes", invisible
Unicode, else { if }).
IOperation is used where it removes syntax casework (conversions,
deconstruction, pattern semantics, checked context); syntax is used where
the edit is spelled, since every fix is a text edit at a syntax span.
A fix that needs a newer API or language level asks the compilation, never
the target framework moniker: Random.Shared is offered when the member
resolves in the references, FrozenSet<T> when the type does, init when
IsExternalInit does, [GeneratedRegex] when the attribute does, using var
when LanguageVersion >= CSharp8. Multi-targeted projects are swept
narrowest first, and a fix is plain everywhere, with the all-frameworks
build as the arbiter. No fix is paired with #if NET8_0_OR_GREATER: that
pairing is not built, and --no-if-defs, which the F# tool uses to turn
its own off, is accepted and has no effect.
The F# principles, restated for Roslyn. None are relaxed; one is added (the speculative check).
- Never break user code. A fix is offered only where it is provably safe; the borderline shape produces no suggestion. A fix must be right WITHOUT a compile: the same fix runs in the editor, where nothing verifies it and nothing puts it back. The tool's per-pass recompile and final build are a backstop against our own bugs, never a licence.
- Guards over removal. When a rewrite is unsafe on some shape, the rule
gains a typed proof that the shape is safe and stands down where the proof
fails; the rule is never deleted or blanket-disabled. Purity proofs are
shared, not per rule:
isPureExpression(literals, locals and parameters not assigned in the scope in question,readonlyfield and get-only property reads,nameof/typeof/sizeof, tuple construction, operators on those with no user-defined overload) andcallsOnlyCore(invocations of members known effect-free:System.String,System.Math,System.MathF,System.Char,Enumerableoperators over pure lambdas,Pathstring functions, tuple andNullablemembers). - The speculative check. Roslyn can re-bind one file in a forked
compilation cheaply:
compilation.ReplaceSyntaxTree(old, patched)then a freshSemanticModel. Every fix that can change name or overload resolution — adding ausing, changing a type, a signature, a receiver, a+operand, a lambda substitution — is applied to a copy of the tree before it is offered, and stands down if the patched file (or the edited member, where the edit stays inside one) carries more errors of any id than before. This turns "a fix must compile without a build" from a discipline into a per-fix proof, at the cost of one file re-bind per candidate finding. It does not compare what each name binds to: a fix that compiles yet rebinds a name — a widenedout varor pattern scope that now captures a field's mention, a new member hiding an inherited one, ausingwhose type a containing-namespace namesake shadows — passes it. Refusing those is each rule's own guard (Text.mentionsName,Text.mentionsNameOutside,Text.declaresName,Guards.declaredUp, a lookup at the use site); the check never replaces a semantic guard (a rewrite can compile and mean something else). - Minimal edits. Trivia outside the edited span is untouched. Roslyn
trivia makes the "comment guard" exact: a fix whose removed span contains
a comment, a
#region, a#pragmaor a#ifline stands down (multi-line fixes never cross a preprocessor directive), and the edited text's comments are compared with the original's before an edit is offered. - Scope gates. A fix that changes a declaration's compiled shape
(
class→record,record→readonly record struct,Tuple→ value tuple,set→init, a signature madeasync) fires onprivate/internal/filedeclarations, and on public ones only under--api-changesorcsharp_refactor.public_api = false. AnOutputTypeofExe/WinExeis a leaf and opens the gate by itself; a library withInternalsVisibleTocloses it forinternaltoo. Editors offer the public-declaration fix anyway, with the "CHANGES THE PUBLIC SHAPE" clause — per-site consent from the one person who can answer. - Serialization cannot be detected, so no rule infers that a shape
change is safe to serialize. The heuristic from FR0157 is kept — a type
named as a
Serialize<T>/Deserialize<T>argument or in aDbSet<T>, carrying[DataContract]/[Serializable]/[JsonSerializable]or a[Json*]/[DataMember]property attribute, stands the shape rules down — and the message says what changes. - Editor offers. Roslyn gives one diagnostic several
CodeActions natively. The first is the auto-applicable fix the CLI takes; the others (Guid.NewGuid()fornew Guid(),CurrentCulturebesideInvariantCulture, the positional form of a record) are editor-only. A rule whose only safe remedy is a design decision is a note (no fix) and prints under--notes. - Performance claims are measured, on both axes, in PerfClaims: a performance rule's rewrite wins on wall clock or allocation, an idiom rule's holds parity, and a slower-but-idiomatic shape goes behind a default-off knob, never into the default. Interned literals and tier-0 JIT are controlled for (runtime-built strings, 5M iterations).
- Nothing is exempted by convention. A rule that is noisy against a
common C# coding standard gets a lower category or default-off, decided
from a sweep over every C# checkout under
C:\git, never a special case for "Try-named methods" and never advice to add a#pragma. - What a gate holds back is reported, not hidden. The run ends with the held-back counts and the config key that would release them.
.editorconfig, because every host already reads it and a C# repository
already has one:
[*.cs]
# per rule: the standard Roslyn switch; none turns the rule off entirely
dotnet_diagnostic.CR0006.severity = suggestion
dotnet_diagnostic.CR0142.severity = none
# rule knobs
csharp_refactor.CR0006.then_at_least = 30
csharp_refactor.CR0006.else_at_most = 2
csharp_refactor.CR0040.sync_swap = true
csharp_refactor.CR0106.utc_now = true
csharp_refactor.CR0145.uses = 6
# run-level keys (read by the tool and the analyzers alike)
csharp_refactor.public_api = false # nothing links to this assembly
csharp_refactor.api_changes = true # --api-changes as a standing decision (implies public_api = false)
csharp_refactor.suppressions = no-correctness # all | no-correctness | none
csharp_refactor.skip_microsoft_duplicates = true # skip what an enabled Microsoft rule already reports (default false)
csharp_refactor.ignore_paths = generated;external/imported
csharp_refactor.hints = csharprefactor.hints # extra CR0011 rules, one per line- Default-off rules are enabled with
dotnet_diagnostic.CRxxxx.severity = suggestion(or--codes CRxxxx, which outranks both the default and anone, as on the F# side;--categoriesnever wakes a default-off rule). csharp-refactor --create-configappends a commented block of every rule and key at its default to the nearest.editorconfig(or writes one) and never overwrites a line that exists.- Suppression is Roslyn's:
#pragma warning disable CR0064,[SuppressMessage("CSharp.Refactor", "CR0064")], severitynone. The tool runsCompilationWithAnalyzerswithreportSuppressedDiagnostics, so thesuppressionspolicy (no-correctness: a pragma on a correctness rule is reported anyway and never auto-fixed;none: every pragma is reported) works as on the F# side, and the run summary counts what pragmas silenced. Editors honour pragmas natively regardless. ignore_paths: additive over the built-in defaults (node_modules,bin,obj,*.g.cs,*.designer.cs,*.generated.cs); a bare name matches a path segment, a slash matches anywhere,*/**are globs.- Tunables are integers or booleans (
true/false/on/off/1/0). - A rule that lays out a rewritten line reads its own
wrap_columnknob, else the file'smax_line_length(the key formatters read), else 120. A malformed value fails open to the default and never breaks the editor. - Precedence is Roslyn's: the nearest
.editorconfigsection wins; the tool reads the sameAnalyzerConfigOptionsthe compiler does, so there is one answer per file.
Every CR rule that shadows a Microsoft rule declares it
(YieldsTo = ["CA2213"]). Per file, the analyzer reads the effective
severity of each shadowed id from the analyzer config options (the SDK
writes a global config with dotnet_diagnostic.CAxxxx.severity for every
NetAnalyzers rule according to AnalysisLevel/AnalysisMode, so the value
is present whenever the analyzers are on):
| Shadowed rule's effective severity | CR rule |
|---|---|
absent (NetAnalyzers off, or not a NetAnalyzers id) or none |
runs |
silent, suggestion, warning, error |
stands down for that id's shapes |
A repository that turns CA2213 on never sees the same finding twice; one
that leaves it at its default (off) gets ours; nothing oscillates. Analyzers
outside the SDK (Roslynator, SonarLint, Microsoft.VisualStudio.Threading.Analyzers,
Meziantou) are not tracked; their overlap is named per rule and left to
.editorconfig.
The tool could also load Microsoft's fix providers from the SDK and apply
CA/IDE fixes in the same verified pass (--with-microsoft). That is v2: it
is what dotnet format analyzers does today without verification; v1
applies CR rules only.
F# rules whose C# shape Microsoft already reports WITH a fix, on by default
at the SDK's default analysis level. A row marked defer gets no CR rule. A
row naming one has its own rule anyway: Microsoft's analyzers are not
always there (a .NET Framework project never loads them) and their fixes
are an editor's, not a sweep's. That rule runs by default and yields only
under csharp_refactor.skip_microsoft_duplicates = true.
(Defaults as of the .NET 9/10 SDK; the gate above is what matters.)
| F# rule | C# shape | Microsoft rule (with fix) | Decision |
|---|---|---|---|
| FR0010 (part) | c ? true : false |
IDE0075 | defer; CR0001 keeps the statement shape |
| — | if (a) return x; else return y; → return a ? x : y; |
IDE0046, IDE0045 | CR0173: the one-line cases, in the fix pipeline; yields to the IDE rules where they are on |
| FR0012 (part) | x == true, .Where(p).Any(), .Count() == 0 |
IDE0100, IDE0120, CA1827 | yields per hint |
| FR0014 | ContainsKey + indexer |
CA1854 | CR0182: the pair's reads proved to see one value (no call, store or await between them unless the dictionary and key are private to the member); yields to CA1854 under skip_microsoft_duplicates |
| FR0015 (hoist) | regex construction hoisted | SYSLIB1045 ([GeneratedRegex]) |
yields; CR0109 covers targets below .NET 7 |
| FR0018 | check-then-add | CA1864 | defer |
| FR0019 | Equals without GetHashCode | CS0659 (compiler) | n/a |
| FR0026 | backing field + trivial get/set | IDE0032 (auto-property) | CR0186: CR0153's field guards, not in a struct or a serialized or laid-out type; yields to IDE0032 under skip_microsoft_duplicates |
| FR0033 | member touching no instance state | CA1822 | defer |
| FR0034 (part) | HasValue ? Value : d |
IDE0029/IDE0030/IDE0270 | defer; CR0004 keeps the payload-use shapes |
| FR0037 (part) | JsonSerializerOptions, SearchValues in loops |
CA1869, CA1870 | yields |
| FR0038 | char overloads | CA1834, CA1847, CA1865–CA1867 | defer |
| FR0039 | ToLower() == |
CA1862 | CR0188: an ASCII literal agreeing with the fold, OrdinalIgnoreCase; yields to CA1862 under skip_microsoft_duplicates |
| FR0040 | redundant ContainsKey before Remove |
CA1853, CA1868 | defer |
| FR0044 | throw ex; |
CA2200 | CR0187: the nearest catch declares ex and nothing writes it; yields to CA2200 under skip_microsoft_duplicates |
| FR0045 | x == double.NaN |
CA2242 | defer |
| FR0048 | placeholder without argument | CA2241 | defer |
| FR0052 | Count == 0 on concurrent collections |
CA1836 | defer |
| FR0053 | BitConverter.ToString().Replace |
CA1872 | defer |
| FR0061 | wrong parameter name in ArgumentException |
CA2208 | defer |
| FR0068 | duplicate enum values | CA1069 | defer |
| FR0077 | missing interface members | CS0535 + "Implement interface" | n/a |
| FR0085 | redundant new |
new T() → new() IDE0090 |
defer |
| FR0095 | lambda restating a method | IDE0200 (method group) | defer |
| FR0097 | redundant parentheses | IDE0047 | defer |
| FR0098 | System.Int32 → int |
IDE0049 | defer |
| FR0106 | Substring → AsSpan |
CA1846 | CR0174: the consumers whose span overload is the same operation (Parse/TryParse, StringBuilder.Append, TextWriter.Write, string.Concat); yields to CA1846 |
| FR0166 | s.Substring(0, 6) = "ORDER-" → StartsWith(…, Ordinal) |
— | CR0175, under a length guard (a short string threw where StartsWith answers false) |
| FR0167 | for c in s.ToCharArray() → for c in s |
— | CR0176, the foreach only (LINQ over a string is slower than over the array) |
| FR0071 | hoist a loop-invariant let above the loop |
— | CR0177: the initializer pure and reading nothing the loop changes; measured, a concatenation 4×, local and readonly-field arithmetic parity (the JIT hoists it; a mutable field is never read) |
| FR0174 | q.ToList().Where(f).Select(g) → q.Where(f).Select(g).ToList() on an IQueryable |
— | CR0178: trivial column comparisons and projections only; a sweep moves exact translations (integers, bool, enums, Guid), the editor offers string, decimal, date and nullable ones |
| FR0118 (omitted token) | forward the CancellationToken |
CA2016 | CR0189 (an optional token left out, or the same method with a trailing token), never in cleanup or a branch the token's state chose; CR0055 keeps the explicit None; yields to CA2016 under skip_microsoft_duplicates |
| FR0124 (count, interpolated template) | template/argument mismatch | CA2017, CA2254 | defer; CR0114 keeps the remainder |
| FR0130 | static readonly constant → const, and a constant local |
CA1802 | CR0172: the field under the API gate (a const is a different member to a compiled consumer), the local always |
| FR0139 | LINQ where a property exists | CA1826, CA1829, CA1860 | defer |
| FR0140 | construct-then-assign → object initializer | IDE0017 | CR0179; yields to IDE0017 under skip_microsoft_duplicates |
| FR0145 | unassigned required members |
CS9035 | n/a |
| FR0155 | seal a class nothing inherits | CA1852 | defer |
F# rules whose C# shape Microsoft reports note-only or off by default get a CR rule WITH the F# guards and, where the F# side has one, a fix; each such rule yields to its Microsoft twin when that twin is on: CA2000 (CR0060), CA1001 (CR0061), CA2213 (CR0062), CA1031 (CR0064), CA2219 (CR0066), CA1065 (CR0067), CA2201 (CR0068), CA2211 (CR0084), CA2214 (CR0086), CA2002 (CR0047), CA1849 (CR0042), CA1851 (CR0030), CA1842/CA1843 (CR0054), CA2016 (CR0055), CA1305 (CR0105), CA2100/CA3001 (CR0120), CA5350/CA5351/CA5359/CA5364/CA5386/CA5397 (CR0125).
Rules with no Microsoft twin at all are the product: the rest of §8.
Columns: category; On = enabled by default; API = fix changes a
public shape, applied only under --api-changes (private/internal always);
Pri = priority (warning severity, printed without --notes); the F#
twin; the Microsoft rule it yields to. "note" in the fix column means the
rule only reports. Guards follow each table; a rule ships with every guard
listed, and a guard that cannot be proven from the typed tree stands the
rule down rather than being dropped.
The catalog as shipped, with each rule's category and default, is Rules.md, which the tests pin to the code; this section is the design it started from and lacks the rules added since. CR0088 was designed here and is not built. The §8.I rules are on but silent below their language level. Priority: CR0034, CR0047, CR0061, CR0062, CR0066, CR0086, CR0107, CR0120, CR0122, CR0123, CR0125, CR0160, CR0161, CR0162, CR0163, CR0165, CR0169, CR0171, CR0190, CR0191, CR0192, CR0193, CR0194.
The guard lists below are the summary. The full conditions come from the
F# implementations, read module by module on 2026-09-19 against this
section: docs/rule-audit.md records, per CR rule, every
condition, alternative shape and knob the F# code enforces that the list
here leaves out (308 items marked port, each with its C# reading), and
the F#-only ones marked n/a so nobody re-derives them. A rule is
implemented against the audit entry plus its guard list here, never the
list alone. Where the audit corrected this section (CR0002's minimum arm
count is a C# decision, CR0064's zero guard is for integer divisors only,
CR0111 needs evidence for both separators, CR0068 leaves plain
Exception to CA2201, CR0103 must check the target type), this section
has been updated in place.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0001 | idiom | v | if (c) return true; return false; / if (c) x = true; else x = false; |
return c; / x = c; |
FR0010 | IDE0075 (ternary) | ||
| CR0002 | idiom | v | if (k == 1) … else if (k == 2) … else … on one scrutinee |
switch (k) { case 1: … } or k switch { 1 => …, _ => … } |
FR0112 | — | ||
| CR0003 | idiom | v | if (s is Circle) { var c = (Circle)s; … } else if (s is Rect) … |
switch (s) { case Circle c: … case Rect r: … } |
FR0103 | — | ||
| CR0004 | idiom | v | x.HasValue ? x.Value + 1 : 0, if (x.HasValue) use(x.Value) |
x is { } v ? v + 1 : 0, if (x is { } v) use(v) |
FR0034 | IDE0029/IDE0030 | ||
| CR0005 | idiom | v | if (a) { if (b) X else E } else E, if (a) { if (b) X } |
if (a && b) X else E |
FR0113 | — | ||
| CR0006 | idiom | if (ok) { twenty lines } else { return; } |
if (!ok) { return; } twenty lines |
FR0114 | — | |||
| CR0007 | idiom | v | x && true, true && x, x || false, false || x |
x |
FR0108 | — | ||
| CR0008 | idiom | v | a || a, a && a |
a |
FR0109 | — | ||
| CR0009 | idiom | v | adjacent case 1: return "x"; case 2: return "x"; / 1 => f(), 2 => f() |
case 1: case 2: / 1 or 2 => f() |
FR0117 | — | ||
| CR0010 | idiom | v | case var x when x == "A":, var x when x == 3 => |
case "A":, 3 => |
FR0129 | — | ||
| CR0011 | idiom | v | term-rewriting hints: !(a == b) → a != b, De Morgan, string.Compare(a, b) == 0 → string.Equals(a, b), a.CompareTo(b) == 0, xs.Select(f).Sum() → xs.Sum(f), xs.Where(p).Count() > 0 → xs.Any(p), xs.Select(x => x) → xs, !xs.Any(p) ↔ xs.All(!p)… |
per hint; extensible per repository | FR0012 | IDE0100, IDE0120, CA1827 per hint | ||
| CR0012 | correctness | v | case Jordan: // not supported yet return null; |
throw new NotImplementedException(); |
FR0100 | — | ||
| CR0013 | correctness | v | switch on an enum whose default: stands in for 1–2 named members |
note; editor: case D: arms plus default: throw new ArgumentOutOfRangeException(nameof(x)) |
FR0072 | — | ||
| CR0014 | correctness | v | switch statement on an enum with no default, every arm exiting, members unhandled |
note; editor: case M: throw new NotImplementedException(); per missing member (≤3) |
FR0110 | CS8509 (expressions) | ||
| CR0015 | idiom | v | for (int i = 0; i < xs.Length; i++) use(xs[i]); |
foreach (var x in xs) use(x); |
FR0101 | — | ||
| CR0016 | idiom | bool done = false; while (!done && …) { … done = true; … } |
note: break/return at the decision |
FR0141 | — | |||
| CR0017 | correctness | v | for (int i …) actions.Add(() => use(i)); |
note: every closure sees the final i; copy into a loop-local |
— | — | ||
| CR0192 | correctness | v | v | x != A || x != B and x == A && x == B over two different constants, x > e && x < e |
note: always true / always false; editor offers the other operator for the constant shapes when the chain is the two comparisons | FR0177 | — | |
| CR0193 | correctness | v | v | if (!x.HasValue) { … x.Value … }, the else of if (x.HasValue), x == null ? x.Value : d on a Nullable<T> |
note: the read throws every time the branch runs | FR0178 | — (CS8629 where nullable analysis is on) | |
| CR0195 | correctness | v | if (done = false), if (a = b), an assignment as an operand of &&/||/!, in ?:, a where or a predicate lambda |
== (literal: the editor also offers the bare test); editor only in lambdas, query clauses and for a variable in a loop condition; a note with the offer where the right side runs something |
— (F# has no assignment expression) | — (CS0665, no fix) | ||
| CR0196 | correctness | v | a non-nullable struct or enum compared with null: if (d == null) S, d != null ? a : b, d == null || p |
the dead test removed with what only it guards; a note elsewhere | — | — (CS0472/CS8073, no fix) |
Guards.
- CR0001 —
cis typedboolwith no user-definedtrue/false/!operator; the statement form requires thereturn false;(or theelse) to be the immediate sibling; the assignment form requires the same target on both sides, a local or a field (a property setter may have effects the order of evaluation would move). - CR0002 — the scrutinee is a local, parameter or
readonlyfield read (evaluated once after the rewrite, where the chain evaluated it per comparison); every comparison is==against a constant ofint/long/char/string/bool/enum type with built-in equality (a user-defined==is a call, and a constant pattern would callEqualsinstead); at least three comparisons (a C# decision — the F# twin has no minimum; two==tests read fine asif/else); branches are single-linereturn/assignment to one target for the expression form, arbitrary blocks for the statement form; a comparison against a non-constant, awhen-shaped extra condition or agotokeeps the chain. - CR0003 — two or more
is Ttests on the same plain identifier; every cast in a branch targets that branch's ownT; no compound conditions; the branches keep their statements verbatim (the cast line becomes the pattern variable, its name kept); a cross-cast or a null check between tests keeps the chain. Theis not null/is nullarms of C# 9 are accepted as patterns of their own. - CR0004 — receiver typed
System.Nullable<T>(a customHasValuenever matches); the pattern variable name is derived from the receiver and checked against every name in scope; withheld where IDE0029/IDE0030 would offer??instead (payload passed through unchanged). - CR0005 — exactly the two semantics-preserving shapes (identical
elseblocks, textually and with no comments lost, or noelseat all); an||-topped condition gains parentheses; the third shape (innerifwithoutelseunder an outerelse) is deliberately absent. - CR0006 —
then_at_least(20) andelse_at_most(3) lines; the negation unwraps an existing!; theelsemust exit (return/throw/continue/break) for the flip to preserve flow. Off by default: happy-path-first is a house style too. - CR0007/CR0008 — operands typed
boolwith no user-defined&/|operator (the&&/||on a user type callstrue/falseand&/|); CR0007 leavesx && falseandtrue || x(the value is constant butx's evaluation goes); CR0008 requires textually identical operands containing no invocation,await,out/refargument, increment or assignment —TryConnect() || TryConnect()is the retry idiom. - CR0009 — contiguous arms only (order is semantics); no
when; no pattern variables (orpatterns cannot bind;case int n:stays); bodies textually identical; neitherdefaultnor the discard arm_joins a run ("A" or _reads as a mistake); the merged form keeps the first arm's position. - CR0010 — the body never mentions the binder; the compared value is a
constant the pattern language can spell (literal,
const, enum member);==is built-in for the scrutinee's type. - CR0011 — the engine is FR0012's:
lhs ===> rhswith single-letter metavariables over Roslyn syntax; a right side that drops or duplicates a metavariable fires only on pure atoms; a hint that changes operator precedence brackets only where needed; each built-in hint names the Microsoft rule it yields to, and a hint is silent inside expression trees (Expression<Func<…>>arguments, typed) where the shape is what a LINQ provider translates. Custom hints come from the file named bycsharp_refactor.hints, one per line. - CR0012 — the comment sits inside the arm, between label and value;
null/default/false/0/-1/string.Empty/empty collection literal stand-ins only under such a comment; only where sibling arms compute. - CR0013 — typed enum, not
[Flags], at most two members unnamed. C# enums are open (any underlying value converts), so expandingdefaultinto named cases changes what an unnamed value does; hence note-only in the sweep, and the editor's expansion keeps adefault:that throws. - CR0014 — switch statements only (the compiler warns on expressions);
every existing arm ends in
return/throw/continue/break-to-exit so that a missing member silently falls out; typed enum, not[Flags]; at most three missing. - CR0015 —
istarts at 0, steps by one, bounded byxs.Length/xs.Countof one array/IList<T>local, parameter orreadonlyfield; every use ofiisxs[i](a use as a value wantsSelect((x, i) => …)and stays the author's call); noxs[i] = …;xsnot assigned, resized or cleared in the body; abreak/continuestays as it is; the element isvaronly whereforeach's own binding (the publicGetEnumerator()pattern first, thenIEnumerable<T>) yields the indexer's type, else that type is spelled (MatchCollectionenumeratesobject), and the speculative check re-binds the loop. Measured:foreachover an array orList<T>compiles to the same loop. - CR0016 — off by default; the note counts the statements that still
run after the flag is raised and says nothing when there are none. C# has
break, so unlike FR0141 the remedy is the keyword, not recursion. - CR0017 — a lambda or local function that mentions the
forvariable and ESCAPES the iteration: stored (Add, assignment to a field or outer local), returned, passed to a deferred LINQ operator (Where,Select, …, materialised outside the loop), passed toTask.Run/ThreadPool/an event. An immediately invoked delegate,List<T>.ForEach,Array.ForEach,Parallel.*and a LINQ chain materialised in the same statement complete inside the iteration and stay quiet.foreachvariables are per-iteration since C# 5 and never fire. CR0160 (§8.J) fixes the shape with the loop-local copy and wins where both report (Rules.overlapWinners).
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0020 | performance | v | xs.ToList().Where(p), xs.ToArray().Select(f).ToList(), foreach (var x in xs.ToList()) |
xs.Where(p).ToList(), xs.Select(f).ToList(), foreach (var x in xs) |
FR0004 | — | ||
| CR0021 | idiom | v | var total = 0; foreach (var x in xs) total += x; (also Math.Max / > running max, min, count) |
var total = xs.Sum(); / .Max() / .Min() / .Count(p) |
FR0050, FR0041 | — | ||
| CR0022 | idiom | bool found = false; foreach (var x in xs) if (p(x)) found = true; |
bool found = xs.Any(x => p(x)); (All for the true-initialised dual) |
FR0107 | — | |||
| CR0023 | performance | v | xs.Where(x => allowed.Contains(x)) where allowed is a startup-built static readonly array/list |
allowed becomes FrozenSet<T> (.NET 8+) / HashSet<T>, or a private companion set when other uses pin the type; else note |
FR0035 | — | ||
| CR0024 | performance | v | foreach (var x in xs) acc.Add(x); |
acc.AddRange(xs); |
FR0030 | — | ||
| CR0025 | performance | v | arr = arr.Append(x).ToArray(), arr = arr.Concat(new[]{x}).ToArray(), Array.Resize(ref arr, arr.Length + 1), imm = imm.Add(x) on ImmutableArray<T>, s += piece on a string, all in a loop |
note: List<T>/ImmutableArray.CreateBuilder/StringBuilder/string.Join |
FR0051, FR0104 | — | ||
| CR0026 | performance | v | xs.ElementAt(i), xs.Count(), xs.Last() on a non-collection IEnumerable<T> inside a loop |
note: materialise once | FR0102 | CA1826/CA1829 (collections) | ||
| CR0027 | correctness | v | xs.Select(x => Log(x)); as a statement; xs.Where(p); discarded |
note: lazy, runs nothing; foreach |
FR0076, FR0017 | — | ||
| CR0028 | idiom | * | var r = new List<T>(); foreach (var x in xs) if (p(x)) r.Add(f(x)); then only read |
var r = xs.Where(p).Select(f).ToList(); |
FR0156 | — | ||
| CR0029 | idiom | v | xs.Select(x => x.A).Select(a => a.B), xs.Select(x => x) |
xs.Select(x => x.A.B), xs |
FR0137 | — | ||
| CR0030 | correctness | v | an IEnumerable<T> parameter enumerated twice on one path (if (xs.Any()) foreach (var x in xs)) |
note: a query or generator runs twice | — | CA1851 | ||
| CR0031 | performance | v | new Random().Next(…) per call or in a loop |
Random.Shared.Next(…) (.NET 6+) |
— | — | ||
| CR0032 | performance | v | foreach (var k in d.Keys) use(k, d[k]) |
foreach (var (k, v) in d) use(k, v) |
— | — | ||
| CR0033 | performance | v | sb.Append(a + b + c) |
sb.Append(a).Append(b).Append(c) |
— | — | ||
| CR0034 | correctness | v | v | foreach (var c in customers) foreach (var o in db.Orders.Where(o => o.CustomerId == c.Id)) |
note: N+1 | FR0028 | — | |
| CR0035 | performance | v | IEnumerable<T> Walk(Node n) { … foreach (var c in Walk(child)) yield return c; } |
note: O(depth) per element; explicit stack | FR0058 | — | ||
| CR0194 | correctness | v | v | list.Add(x);, _ = list.Add(x); on a System.Collections.Immutable collection; s.Trim(); on a string |
note: the call returns the new value and the statement drops it; editor offers list = list.Add(x); for a local or value parameter |
FR0179 | CA1806 (the string shape) |
* CR0028's default was decided by PerfClaims at M2 (benchmarks/PerfClaims/RESULTS.md):
parity on arrays and lazy sequences, 3.8× slower on List<T>, so it ships
default-off. The same run put CR0022 off by default (Any(pred) is 4.5–6.5×
slower than the flag loop when nothing matches), gated CR0021's Sum/Count
to array and List<T> sources, CR0024 to collection sources, and dropped
Select from CR0020's movable stages.
Guards.
- CR0020 — typed
Enumerablecalls over a source that is not anIQueryable(a query's copy runs the query; the loop would run over an open reader, a moved stage would be translated by the provider); the moved operation must shrink or consume (Where,First,Any,Count,Take,foreach), each pair measured; the lambda must not mutate the source or name it (the snapshot idiom:foreach (var x in list.ToList()) list.Remove(x)keeps its copy — a body that callsAdd/Remove/Clear/an indexer set on the source, or passes it to a method, stands the rule down); aToList()whose result is enumerated more than once stays. - CR0021 — the accumulator is a local initialised to the identity and
assigned only by the one
+=/Math.Max/>-compare in the loop body and read only after; the source is an array,List<T>orIEnumerable<T>local. Overflow:Enumerable.Sumis checked where+=wraps, soint/longsums rewrite only when the compilation'sCheckOverflowoption is on or the loop sits in acheckedblock;float/double/decimalalways (decimalthrows either way).Max/Minon floating types never (the>loop andEnumerable.Maxdisagree on NaN). Measured: .NET 8+ vectorisesSum/Min/Maxonint[]/long[]/List<int>, so this is a win there and parity elsewhere. A general combine stays a loop:Aggregateis not clearer thanforeach. - CR0022 — the loop body is the one
ifwith noelse, optionally after pure single-linevarbindings that fold into the lambda; the predicate isisPureExpression/callsOnlyCore(short-circuiting must not skip an effect); the flag is not read inside the loop and not reassigned after; measured: parity on arrays; onList<T>Enumerable.Any(pred)boxes the struct enumerator — if PerfClaims shows that allocation theList<T>shape goes behind a knob (csharp_refactor.CR0022.lists). - CR0023 — the collection is a
static readonlyfield or a local initialised once from a literal, never reassigned or mutated (typed: noAdd/Remove/indexer set anywhere in the compilation); the probe isContainsinside a loop or a lambda handed to a collection operator; the element type has value equality; when every use is aContainsthe declaration becomesFrozenSet<T>(capability-gated) orHashSet<T>, otherwise a companion set is declared beside it; measured with the build cost charged; probing the loop variable itself never fires. - CR0024 —
Addresolves toList<T>.Add(typed), the body is that one statement of the loop variable, the source is not the list itself. - CR0025 — note only; the string form requires the typed
string+=and any loop;ImmutableArray<T>typed; a single-elementConcat/Appendoutside a loop is not reported. - CR0026 — receiver typed as an
IEnumerable<T>that is NOTIList<T>/ICollection<T>/IReadOnlyCollection<T>(those get CA1826/ CA1829); the loop is not the one that produced the enumerable;Count()in aforcondition counts. - CR0027 — expression statement whose value is a typed
IEnumerable<T>from a deferredEnumerableoperator, or a discarded call result of one;_ = xs.Select(…)is a decision and stays quiet; the note names the effect the lambda contains. - CR0028 — every use of the list between declaration and loop is none,
inside the loops is a statement-position
Add(never undertry, a lambda or aCountcap), after the loops is a read (foreach, LINQ,Count, indexer read, passing to a parameter typedIEnumerable<T>/IReadOnlyList<T>/List<T>); the loop bodies areif/foreachnests over pure conditions and projections;await,yield, a second collection filled, or a mutation after the loop stands it down; theSelectlambda must not close over aref/Span(cannot be captured). - CR0029 — both calls resolve to
Enumerable.Select(anIQueryablechain is a query the provider translates), and the chain is not inside an expression tree (there too the lambdas are the provider's as written); both lambdas are expression lambdas; substituting the first body for the second's parameter duplicates nothing (the parameter is used once, or the first body is a pure atom) and captures nothing (names checked);Select(x => x)is removed only where the result type is unchanged (typed). Both forms are already lazy and per-element, so this is an idiom rule; measured parity (the runtime already composes consecutiveSelects). - CR0030 — the parameter's declared type is
IEnumerable<T>(not a collection interface); two enumerations on one control-flow path (foreach, a materialising or consuming LINQ call,GetEnumerator); an argument that is a literal array or a collection at every call site in the compilation does not rescue the method — the note is about the signature's promise. - CR0031 — parameterless
new Random()(a seed is a decision) whose instance is used only for calls in the same expression or scope and never stored;Random.Sharedresolvable; measured (allocation, andRandom's seeding cost). A seed built only from fine-grained clock, thread or process reads (DateTime.Now.Millisecond,.Ticks,Environment.TickCount,Guid.NewGuid().GetHashCode(), arithmetic and casts over those) is no decision and takes the same fix; a coarse part of the clock (.Hour,.DayOfYear), another operand or a constant alone stays. WithoutRandom.Sharedthe clock seed is a note. - CR0032 —
dtypedDictionary<K,V>/IDictionary<K,V>, the body readsd[k]and never writesd; the deconstruction form needs C# 7. - CR0033 —
AppendonSystem.Text.StringBuilderwith a+chain of typed strings (a+on other types converts throughToString()insideAppendanyway);$""arguments are left alone (.NET 6+ handles them without an intermediate); measured. - CR0034 — typed
IQueryable<T>enumerated in a loop nested in another; an outer loop over a chunked source (Chunk, aSkip/Takepage) is a batch and stays quiet; a member of an anonymous row built in aQueryableprojection is part of the outer statement and stays quiet. - CR0035 — an iterator method that yields from a
foreachover its own recursive call; a tailreturn Walk(child)(noyield) is a redirect and does not count; note only.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0040 | correctness | v | inside an async method: t.Result, t.Wait(), t.GetAwaiter().GetResult(), Task.WaitAll(a, b), a.Result inside t.ContinueWith(a => …) |
await t, await Task.WhenAll(a, b), the continuation as an await bind; outside async: boundary note, sync-twin swap editor-only or sync_swap |
FR0049 | CA1849 (Thread.Sleep) |
||
| CR0041 | correctness | v | v | a sync method draining a task at its boundary (return Foo().Result;) whose every caller sits in an async context |
method becomes async Task<T> (Async suffix unless configured off), drains become await, every caller awaits |
FR0049 (taskify) | — | |
| CR0042 | correctness | v | inside an async method: reader.ReadLine(), stream.Read(…), File.ReadAllText(…) where an …Async twin exists |
await reader.ReadLineAsync() |
FR0119 | CA1849 | ||
| CR0043 | correctness | v | async void M() that is not an event handler |
async Task M(); call sites in async contexts gain await |
— | VSTHRD100 | ||
| CR0044 | correctness | v | a Task-returning call as an expression statement in a NON-async method, Task.Run(…); discarded |
note: nobody observes a failure; _ = … is a decision |
FR0149, FR0017 | CS4014 (async methods) | ||
| CR0045 | performance | v | [Fact] public void T() { var r = Load().Result; … }, Assert.Throws<E>(() => t.Wait()), Task.WaitAll(a, b) in a test |
public async Task T() { var r = await Load(); … }, await Assert.ThrowsAsync<E>(() => t), await Task.WhenAll(a, b) |
FR0142 | — | ||
| CR0046 | performance | v | async Task<T> M(x) { return await Inner(x); } with nothing else in the body |
Task<T> M(x) { return Inner(x); } |
— | — | ||
| CR0047 | correctness | v | v | lock (this), lock ("cache"), lock (typeof(T)), lock (x.GetType()) |
note; editor: a private readonly object _gate = new(); (or System.Threading.Lock on .NET 9+) beside the locked value |
FR0046 | CA2002 | |
| CR0048 | correctness | v | Monitor.Enter(x); try { … } finally { Monitor.Exit(x); } |
lock (x) { … } |
FR0123 | — | ||
| CR0049 | correctness | v | if (!cd.TryGetValue(k, out var v)) { v = Compute(); cd[k] = v; } on a ConcurrentDictionary |
the miss arm becomes v = cd.GetOrAdd(k, _ => Compute()); |
FR0154 | — | ||
| CR0050 | correctness | v | cd.GetOrAdd(k, factory) whose value type is Task/ValueTask/Lazy |
note: a faulted value stays cached | FR0152 | — | ||
| CR0051 | correctness | v | Task<T> M() { using var x = …; return DoAsync(x); } |
async Task<T> M() { using var x = …; return await DoAsync(x); } |
FR0150 | — | ||
| CR0052 | correctness | v | AppDomain.CurrentDomain.ProcessExit += (s, e) => this.Flush(); (a this-capturing handler on a process-wide or static publisher, never removed) |
note: the object lives as long as the publisher | FR0027 | — | ||
| CR0053 | correctness | v | list.ForEach(async x => …), Parallel.ForEach(xs, async x => …): an async lambda converted to a void-returning delegate |
note: async void in disguise |
— | VSTHRD101 | ||
| CR0054 | performance | v | Task.WhenAll(new[] { t }), Task.WaitAll(t) |
note: the direct form changes the result type | FR0079 | CA1842/CA1843 | ||
| CR0055 | correctness | v | Foo(x, CancellationToken.None) / Foo(x, default) while a token parameter is in scope |
Foo(x, ct) |
FR0118 | CA2016 | ||
| CR0198 | correctness | v | request.Headers.Add("PLAID-SECRET", secret), req.Headers.Add(h, v) in a file that never sets AllowAutoRedirect = false |
note: a redirect carries the header | FR0183 | |||
| CR0199 | correctness | new HttpClient(), WebRequest.Create(url), new WebClient() in a file that never turns redirects off |
note, off by default | FR0184 | ||||
| CR0197 | correctness | v | try { t.Wait(); } catch (IOException) { … } — also Result, Task.WaitAll — with no clause for AggregateException |
note; editor: a clause for the wrapper filtered on InnerException or GetBaseException(), or the removal of a clause nothing reaches |
— | — |
Guards.
- CR0040 — receivers typed
Task/Task<T>/ValueTask/ValueTask<T>; the bind fix needs a direct statement of theasyncbody (var x = t.Result;,t.Wait();,Task.WaitAll(…)in statement position), never inside a lambda, alock(await is illegal there), acatch/finally, or a body choreographed around a thread (Thread, a signal,Interlocked);.Resultwraps inAggregateExceptionwhereawaitunwraps, so acatch (AggregateException)around the site stands the fix down and the note says why; quiet when the task is known complete (IsCompletedprobe,Task.FromResult,CompletedTask, after its ownWait(timeout)); the spine of a non-asyncMainand of a.csxtop level is the console's blocking point and gets no boundary note; the sync-twin swap (X.FooAsync().GetAwaiter().GetResult()→X.Foo()when the typed tree proves the sibling) is editor-only orsync_swap, never auto-applied: the tool does not walk code backward from async.GetAwaiter().GetResult()is never emitted by any rule. - CR0041 —
privatemethods always,internalunder the scope gate, public only with--api-changesand every referencing project in the run being C#/VB; every caller must be a bindable statement in anasyncbody (or a test that CR0045 converts in the same pass); one unconvertible caller vetoes everything; the speculative check re-binds every touched file; the suffix is added when the name lacks it and no clash results (csharp_refactor.CR0041.async_suffix = falsekeeps the name);out/refparameters, iterators,unsafeand overrides veto (an override's shape is the base's). - CR0042 — the twin is proven from the typed tree: same name plus
Async, same parameter prefix,T→Task<T>/ValueTask<T>return, a trailing optionalCancellationTokentolerated (CA2016 hands it the token on the next pass); statement position orvar x = …only; not in alock/catch/finally/lambda/thread-choreographed body; never a LINQ twin overIQueryable<T>(EF's async query extensions need an async query provider; an in-memory source throws). - CR0043 — not
(object, EventArgs)-shaped, not subscribed to any event in the compilation, not an override or interface implementation, no[…Handler]-style attribute; the fix changes the signature and addsawaitat call sites inasynccontexts; a call site in a sync context would become a silent fire-and-forget, so it vetoes the fix and the rule notes instead. - CR0044 — typed
Task-returning expression statement; a.ContinueWith(…, TaskContinuationOptions.OnlyOnFaulted), a stored task, or an explicit discard is handled; the note distinguishes .NET Core's silent unobserved exception from the F# side's process kill. - CR0045 — test attributes of xUnit, NUnit, MSTest, TUnit;
public void→public async Task; spine-level blocking sites only; the framework's async assert is spelled per framework (Assert.ThrowsAsyncfor xUnit and NUnit,Assert.ThrowsExceptionAsync/ThrowsAsyncfor MSTest by version); a test whose last expression is a value stays; a body choreographed around a thread stays. - CR0046 — the body is exactly
return await e;(or=> await e);eis an invocation of a method the typed tree marksasync(an async callee never throws synchronously, so the only observable difference — a sync throw where the caller got a faulted task — cannot occur) with pure-atom arguments; noConfigureAwait; nousing,try,lock,foreachorawait usingin the method; return types match exactly. Measured: one state machine and its allocation fewer. - CR0047 — typed: the operand is
this, astring, aType, or a boxed value type; the editor's lock object lands beside the field the body guards or before the enclosing member;System.Threading.Lockis offered where it resolves and the file is C# 13; the initialiser isnew()from C# 9 andnew object()below. (The gate's language version came out of the property suite: an offer spelled C# 13 into a C# 10 file.) - CR0048 — single-argument
Enter(theref bool takenoverload carries protocol), identical operand text inEnterandExit, thetry/finallyimmediately follows; a bareEnterwith notryis the leak note. - CR0049 — typed
ConcurrentDictionary; the miss arm computes and stores through the indexer,TryAdd(k, v)discarded, orAddOrUpdatereturning the same value; the hit path keepsTryGetValue(measured: 2.1 ns and no delegate on the hit against 7.3 ns and 64 B forGetOrAddwith a lambda); a key that is not a pure atom, a factory reading aref/Span/outlocal (cannot be captured), or aLazy/delegate value type stands it down; the message carries theLazy<T>hint when the factory calls something. - CR0050 — gated on the value type argument; a factory that merely throws caches nothing and is not reported.
- CR0051 — the shape only exists in non-
asyncmethods (anasyncmethod cannotreturna task); the disposable is read by the returned task's arguments or captured by its lambda; the method becomesasyncand the message states the timing change (argument evaluation exceptions now fault the task). This is a correctness fix; the F# editor-only stance was for a different remedy (moving the binding). - CR0052 — the publisher is
AppDomain.CurrentDomain.*,Console.CancelKeyPress,SystemEvents.*, astatic event, or anIObservablefrom a static/singleton member; no matching-=/Disposeof the subscription in the type; a handler on an event of an object the same scope created stays quiet. - CR0053 — typed: an
asynclambda whose target delegate type returnsvoid(Action<T>, an event handler type);Task.Run(async () => …)andFunc<Task>targets are fine. - CR0055 — exactly one token parameter on the enclosing member; the
call resolves to a method whose parameter at that position is
CancellationToken; never inside acatch/finally(a cancelled operation must still roll back), and never where theNoneis bound to a name.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0060 | correctness | v | var s = new FileStream(…); never disposed, every mention in scope |
using var s = new FileStream(…); (C# 8+); advice naming the destination when handed off |
FR0075 | CA2000 | ||
| CR0061 | correctness | v | v | a type that constructs a disposable field and does not implement IDisposable |
note | FR0032 | CA1001 | |
| CR0062 | correctness | v | v | a Dispose that never releases one of the type's own new-constructed disposable fields |
note (Cancel without Dispose named separately) |
FR0047 | CA2213 | |
| CR0063 | correctness | v | public void Dispose() on a type not implementing IDisposable |
note: nothing can using it |
FR0148 | — | ||
| CR0064 | correctness | v | catch { }, catch (Exception) { return null; }, catch (Exception) when (true)… |
note; editor: TryParse for a one-call Parse body, a zero guard for a pure division, an IO-only catch for file IO, a log line in the file's logging idiom |
FR0055 | CA1031 | ||
| CR0065 | idiom | v | catch (E ex) { if (!Cond(ex)) throw; … } |
catch (E ex) when (Cond(ex)) { … } |
— | — | ||
| CR0066 | correctness | v | v | throw inside finally |
note | FR0063 | CA2219 | |
| CR0067 | correctness | v | throw inside Equals/GetHashCode/ToString/Dispose/a static constructor |
note | FR0054 | CA1065 | ||
| CR0068 | correctness | v | new NullReferenceException(), new IndexOutOfRangeException(), new OutOfMemoryException()… |
note | FR0064 | CA2201 | ||
| CR0069 | idiom | v | v | throw new InvalidOperationException("Error"); with a constant message |
throw new InvalidOperationException($"Error, calling {nameof(M)} with x: {x}"); |
FR0092 | — | |
| CR0070 | correctness | v | catch (ReflectionTypeLoadException e) { Log(e.Message); }, catch (AggregateException e) { Log(e.Message); }, WebException, SqlException |
note; editor for ReflectionTypeLoadException: use e.Types filtered of nulls, or join LoaderExceptions |
FR0151 | — |
Guards.
- CR0060 — typed
IDisposableconstruction (new, and theCreate()factories ofMD5/SHA*/Aes/RandomNumberGenerator);using varneedsLanguageVersion >= 8, otherwise ausing (…) { }block is offered only when the binding heads its block; every mention stays in scope; ownership transfers are not leaks: returned (also inside a tuple, record,Some-like wrapper), stored in a field/property/collection/static, passed to another disposable's constructor (new StreamReader(stream)), passed to a same-file method that disposes its parameter (read one hop); handed to a method that keeps it names the leak; aClose()/Dispose()call anywhere in scope exempts;HttpClientis never ausingcandidate (a shared instance orIHttpClientFactoryis the right lifetime — CR0110's note);StringReader/StringWriter/MemoryStreamover a caller's buffer own nothing; a task the disposable produced and handed to any call is in flight; aCancellationTokenSourcewhose token reaches anything but an awaited BCL call is in flight; in an ASP.NET controller/hub member the leak is per request and carries warning weight. - CR0061 — injected constructor parameters do not count (the injector
owns them); an interface inheriting
IDisposablecounts; the no-ownership types above are not noted. - CR0062 — the interface
Disposeis followed one hop intoDispose(bool);base.Dispose()hand-off and aSystem.Reactivefile (unsubscribe-not-release) stay quiet;Cancel/ClosewithoutDisposegets its own wording. - CR0064 — catch-all means
catchorcatch (Exception)without a filter, or with a constantwhen (true); a specific type ignored is a decision, and so is a filter, on the exception or on state; theboolprobe idiom (try { …; return true; } catch { return false; }) is quiet; a catch-all after a cancellation rethrow arm, or followed by an unconditional failure, is a decision; the one-call teardown idiom (try { x.Dispose(); } catch { }) and a try around a non-throwing probe (File.Exists) are named for what they are; test files (a test frameworkusingor attribute — the one predicate CR0064, CR0069 and CR0146 share) are quiet. The editor's IO-only narrowing requires the typed tree to agree every call in the body isSystem.IO's. The zero-guard offer is for an INTEGER divisor only:decimal+/*//throwOverflowException, so the catch guarded more than the division, and float division never throws. - CR0065 — the condition reads only the exception's members, literals
and pure atoms (a filter runs BEFORE inner
finallyblocks, so an effectful condition would reorder effects); the rethrow isthrow;(notthrow ex;— CA2200's business); the guard is the first statement of the handler. - CR0066/CR0067/CR0068 — throws the block itself catches stay quiet; a switch whose arms throw three or more distinct types is a fault table and stays quiet (CR0068).
- CR0069 — constant message only; quotes only arguments whose type prints (primitives, strings, enums — not a record, which prints every member it carries); quiet on invariant messages (unreachable, not possible, NYI, internal error), in security-named scopes, in test files, where the same literal appears elsewhere in the compilation (a test asserting on it), and where the message is the member's own name. Exception text is observable behaviour: API-gated.
- CR0070 — a table by exception type:
ReflectionTypeLoadException→LoaderExceptions/Types,AggregateException→InnerExceptions/Flatten(),WebException→Response,SqlException→Errors/Number; reading the informative member anywhere in the handler or its filter counts as informed; the RTLE editor fix keeps the rethrow for the nothing-loaded case and appends a// TODO: log e.LoaderExceptions.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0080 | idiom | v | v | a class whose every instance member is a get-only/init property or a constructor assigning them |
record (positional form as an editor alternative) |
— | — | |
| CR0081 | performance | v | v | a record (or CR0080 class) of at most four small unmanaged fields |
readonly record struct |
FR0070 | — | |
| CR0082 | performance | v | v | Tuple<int, string> in a private/internal signature or field, Tuple.Create(a, b) |
(int, string), (a, b) |
FR0093 | — | |
| CR0083 | idiom | v | v | { get; set; } assigned only in constructors and object initialisers of the type across the compilation |
{ get; init; } (C# 9+, IsExternalInit resolvable) |
— | — | |
| CR0084 | correctness | v | public static int Counter; assigned from two or more sites or from itself |
note; editor: private/readonly |
FR0062 | CA2211 | ||
| CR0085 | correctness | v | x.GetType().Name == "Customer", x.GetType() == typeof(T) |
note | FR0036 | — | ||
| CR0086 | correctness | v | v | a constructor calling a virtual/abstract member of its own type |
note | FR0020 | CA2214 | |
| CR0087 | performance | v | status.ToString() == "Active" on an enum |
status == Status.Active |
— | — | ||
| CR0088 | idiom | v2 | v | a closed set of string literals matched by name across parameters, fields and call sites | an enum plus a ToText() extension returning the original literal, every slot retyped |
FR0157 | — | |
| CR0089 | idiom | v | a private type's DateTime field written from DateTime.Now/UtcNow and read through parity members |
DateTimeOffset in one edit set |
FR0134 | — | ||
| CR0090 | correctness | v | new Guid(), default(Guid) spelled as a constructor call |
Guid.Empty; editor: Guid.NewGuid() |
FR0136 | — |
Guards.
- CR0080 — no mutable instance state (every field
readonly, every property get-only orinit, every property an auto-property — a getter with a body is behaviour, a lazy initialiser or a computed value, not data held; no method assignsthisstate); no base class other thanobjector a record; noEquals/GetHashCode/==override; reference identity is not relied on anywhere in the compilation (==/!=on two instances,ReferenceEquals,lockon an instance, use as a dictionary key or set element with the default comparer — a record changes equality, which is the point and the risk); the serializer heuristic; no[StructLayout]/unsafe; scope-gated because equality is API. The fix changesclasstorecordand nothing else; the positional rewrite is an editor alternative. - CR0081 — fields all small unmanaged structs or enums, total ≤ 32
bytes; no inheritance either way; no interface beyond the compiler's
IEquatable<T>; not used asT?anywhere (that spelling would change from a nullable reference toNullable<T>), not compared withnull, not boxed toobject/an interface, notlocked, not a type argument (spelled or inferred) of aclass-constrained parameter, in this compilation or a C# project referencing it;readonly record structneeds C# 10; measured on the allocation axis. - CR0082 —
Tuple<…>typed; private/internal members and fields (a public signature is API);Item1..ItemNnames are shared byValueTupleand stay; null comparisons of the tuple veto; use throughITupleor reflection vetoes; an argument use is simple only where the call binds and the parameter it lands in (of the callee's definition, not its instantiation) is a source declaration of the same tuple type in the compilation, retyped together — a library'sTuple<…>, a type parameter,objector an unbound callee vetoes; the serializer heuristic (aValueTuple's elements are fields, which System.Text.Json ignores by default — a shape change); the speculative check re-binds every touched file; measured on allocation. - CR0083 — every assignment to the property in the compilation is in an
object initialiser, a
withexpression, or a constructor of the declaring type; noPropertyInfo.SetValue/nameof(P)reflection shape;initneedsIsExternalInit(resolvable, or the project polyfills it); public setters are API (an external caller assigning after construction breaks); Entity Framework entities (DbSet<T>heuristic) stand down. - CR0084 — churn gate: two or more assignment sites or a self-update;
a set-once seam stays quiet;
private/internaltypes stay quiet. The editor offersprivatealways andreadonlyonly where every write is a constructor's (a method's write is what the note is about, andreadonlywould not compile there). - CR0086 — the callee is
virtual/abstracton the constructed type or a base, notsealed-overridden in this type; asealedclass stays quiet (nothing can override). - CR0087 — typed enum, literal equal to a member name (case-sensitive),
not
[Flags],ToString()parameterless; measured (an enumToString()allocates and consults a cache). - CR0088 — v2. The flow proof and adapters of FR0157 port; the C#
landing shape is an
enum(an enum cannot overrideToString, so the original text lives in a generatedToText()extension and every print site calls it), which is a larger edit than the F# union; editor-only until the sweep proves it. - CR0089 — off by default (a serialization-shape change); the strict envelope of FR0134.
- CR0090 — typed
System.Guid;Guid(bytes)and friends are deliberate.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0100 | idiom | v | "Hello " + name + "!" |
$"Hello {name}!" |
FR0031 | — | ||
| CR0101 | idiom | v | string.Format("{0} of {1:N2}", a, b) |
$"{a} of {b:N2}" |
FR0042 | — | ||
| CR0102 | performance | v | $"{x.ToString()} items", string.Join(", ", xs.Select(x => x.ToString())) |
$"{x} items", string.Join(", ", xs) |
FR0021 | — | ||
| CR0103 | cosmetic | v | $"no holes" |
"no holes" |
FR0086 | — | ||
| CR0104 | idiom | v | x == null || x == "", x is null || x.Length == 0, x == null || x.Trim() == "" |
string.IsNullOrEmpty(x), string.IsNullOrWhiteSpace(x) |
FR0138 | — | ||
| CR0105 | correctness | v | double.Parse(s), DateTime.Parse(s), Convert.ToDecimal(s) without a provider |
editor: CultureInfo.InvariantCulture (primary) / CurrentCulture; CLI under invariant |
FR0067 | CA1305 | ||
| CR0106 | correctness | v | DateTime.UtcNow.Date, DateTime.Today (notes); DateTime.Now |
DateTime.UtcNow under utc_now; editor always |
FR0121 | — | ||
| CR0107 | correctness | v | v | new Regex("(unclosed"), Regex.IsMatch(s, "[") |
note: guaranteed ArgumentException |
FR0122 | — | |
| CR0108 | performance | v | Regex.IsMatch(s, "^abc"), Regex.Replace(s, "abcd", "x") with a plain literal |
s.StartsWith("abc", StringComparison.Ordinal), s.Replace("abcd", "x") |
FR0015 | — | ||
| CR0109 | performance | v | new Regex("lit") or Regex.Match(s, "lit") inside a loop or a per-call method |
[GeneratedRegex("lit")] private static partial Regex LitRegex(); (.NET 7+, the type made partial) or a static readonly Regex field below that |
FR0015, FR0037 | SYSLIB1045 | ||
| CR0110 | performance | v | new HttpClient() per call or in a loop; MD5.Create()/SHA256.Create() in a loop |
note | FR0037 | CA1869/CA1870 (their types) | ||
| CR0111 | idiom | v | dir + "\\" + file, dir + "/" + file with path evidence |
note: Path.Combine/Path.Join |
FR0081 | — | ||
| CR0112 | correctness | v | bidi controls, Unicode tag block, zero-width spaces, mid-file BOM in source | \u200B escape inside a regular string; note elsewhere |
FR0125 | — | ||
| CR0113 | correctness | v | balance + 2_000_000_000, seconds * 1_000_000 on int |
note; editor: widen to long, or checked(…) |
FR0105 | — | ||
| CR0114 | correctness | v | duplicate placeholder names in a log template; Serilog templates with the shapes CA2017/CA2254 do not cover | note | FR0124 | CA2017, CA2254 | ||
| CR0115 | correctness | v | catch (Exception ex) { _log.LogError("sync failed {Id}", id); } |
_log.LogError(ex, "sync failed {Id}", id); |
FR0120 | — | ||
| CR0190 | correctness | v | v | d.ToString("yyyyMMddhhmmss"), d.ToString("yyyy-mm-dd"), $"{d:HH:MM}" on a date or time type |
"yyyyMMddHHmmss", "yyyy-MM-dd", "HH:mm"; editor only at ParseExact/TryParseExact |
FR0175 | — | |
| CR0191 | correctness | v | v | new DateTime(now.Year, now.AddMonths(-1).Month, 25) |
new DateTime(now.AddMonths(-1).Year, now.AddMonths(-1).Month, 25); a note for a receiver that runs a call and for a day of the shifted instant |
FR0176 | — |
Guards.
- CR0100 — every operand a literal or a typed
stringexpression, the+resolving to string concatenation (a user-defined+never rewrites); literals containing{/}stand down; withDefaultInterpolatedStringHandlerresolvable any hole type is fine; without it (netstandard2.0, net4x) an interpolation with a non-string hole lowers tostring.Format, so only all-string chains rewrite there; as an argument, the call must bind to the same member once the string is interpolated (an interpolated string converts toFormattableString,IFormattableand handler types too — EF Core'sExecuteSqlCommand(FormattableString)would take it over(RawSqlString)and parameterise a table name;Guards.bindingKept); measured on .NET 8+ (the handler beatsConcatpast two parts and matches it below). - CR0101 — a literal format, no
IFormatProviderargument (culture is a decision), noparams object[]passed as one array, every placeholder index within range (CA2241's business otherwise); format and alignment carried into the hole;{{/}}kept; an argument used twice must be a pure atom; a call laid out over lines must fit the wrap column as one; the same handler gate and the same-overload guard as CR0100. - CR0102 — typed: the
ToString()is parameterless and the hole has no format/alignment, or theJoinreceives anIEnumerable<T>whoseTis the projected element (the genericJoin<T>overload resolvable); on .NET 6+ the handler formats without boxing, which is the measured win. - CR0103 — the site must convert the string to
string(orobject): aFormattableString/IFormattabletarget, or a parameter that only accepts an interpolated-string HANDLER, wants the$(the F# twin lostlet s: FormattableString = $"…"this way). A hole-free$"…"is a constant string, so a method with both astringand a handler overload binds thestringone and the fix is safe there. Typed: the converted type answers; parse-only: any argument position,return, typed declaration or assignment keeps its$,var x = $"…"and a+operand do not. - CR0104 — subjects are identifiers or dotted pure reads;
Trim()with no arguments strips exactly theIsWhiteSpaceset; the barex.Trim() == ""without a null guard is editor-only (null throws today). - CR0105 —
double/float/decimal/DateTime/DateTimeOffset/TimeSpanparses; integer parses stay quiet; the primary is spelled short under an existingusing System.Globalization.Convert.ToDecimal/ToDouble/ToSingle/ToDateTimeon one argument typedstringare the same parse and take the same fix; their other overloads are quiet. - CR0106 —
DateTime.Now.Date-style calendar reads are excluded from theUtcNowfix (swapping underneath one manufactures the first bug);Nowhanded to a non-UTC timestamp setter (File.SetLastWriteTime) stays. - CR0108 — declined wherever
RegexandStringdiffer: a$in the replacement, an empty pattern, an anchorReplacecannot carry, a$anchor before a final newline,RegexOptionsorMatchEvaluatoroverloads; the ordinalStartsWithoverload is spelled. - CR0109 — literal pattern, constant options, single-line construction;
a pattern the engine rejects is CR0107's (hoisted into a generated regex
it would fail the build, where the call only threw when reached);
[GeneratedRegex]resolvable and the containing type chain declared in this file (every part gainspartial); otherwise aprivate static readonly Regexfield above the member's doc comment; a name clash is a note; one member per pattern and options in a type (a second site refers to the first's member, an existing static field or generated method is reused); a binder namedregex/rx/patterndoes not name the member. - CR0110 —
HttpClient's note names the lifetime question rather than a fix; the crypto factories fire only inside loops. - CR0111 — BOTH separators need positive path evidence (path-ish names,
rooted or extension literals, a literal existing on disk): a lone backslash
used to fire alone until escape-sequence building (
result + "\\" + c) showed where that goes wrong; a chain opening with/needs the stronger evidence (a web route); URL-shaped chains never fire; a join only compared or searched for is a key; a separator only joins with text on both sides. - CR0112 — ZWJ/ZWNJ are exempt (emoji, Arabic and Persian text).
- CR0113 — decimal spellings only; unsigned skipped; a file inside a
checkedcontext or a compilation withCheckOverflowon is left alone. - CR0114/CR0115 — typed
Microsoft.Extensions.Loggingand Serilog; ANY mention of the exception in the arguments counts as handled,ex.Messageincluded (a PII choice the rule must not escalate). - CR0190 — a string literal format only, read as runs of one letter
with escaped characters and quoted sections skipped; the receiver, hole
or parse owner is
DateTime/DateTimeOffset/DateOnly/TimeOnlyby symbol (neverTimeSpan, whose only hour specifier ishh);hh→HHwith notrun in the format;mm→MMbeside ay/drun and beside noh/H/srun, when everyMrun is itself a month among the time parts (or there is none);MM/M→mm/mafter anh/Hrun or before ansrun and beside noy/drun, when everymrun is itself minutes among the date parts (or there is none) — a swapped pair has both repaired, a rightly placed run vouches for the other; an escaped character or a quoted section between two runs parts them; one-character formats,%, an unclosed quote and a literal whose source is not its value (C# escapes) stand it down; the edit changes letters inside the literal only. Thehh→HHrepair is swept only in a timestamp (ay/M/drun in the format) of a file where no other text renders the designator (AM/PM as a word, a format with atrun) and noParseExactreads anhformat; otherwise it is an editor offer. AParseExact/TryParseExactformat is an editor offer (what a parser accepts is the author's call). Not inside an expression tree, not in a test file; an interpolated string only where it is astring. - CR0191 —
DateTime/DateTimeOffset/DateOnlyconstructors taking(year, month, day, …)by position; the year isX.Year, the monthY.Month, one receiver the other plus a singleAddMonths/AddDays/AddYears; the fix (the part reading the plain instant reads the shifted one) needs a receiver of locals, parameters, fields and properties and an amount that is a literal or a name, negated or not — otherwise a note; a sweep applies it only where the YEAR reads the plain instant (the date then changes at a year boundary only), the reverse is an editor offer.AddYearskeeps the month: the shifted year beside the plain month is quiet, the shifted month beside the plain year a note. A day from the instant shifted against the year's and month's is a note. - CR0195, CR0196, CR0197 (tabled in §8.A and §8.C) — the guards are
the rules' sections in Rules.md. A sweep applies CR0195's
==only in a statement's condition or?:(never per element, never a variable in a loop's condition, never a first write) and CR0196's removal only for a plain operand, a lifted comparison and a rewrite that drops no comment and leaves nothing unreachable; CR0197 is a note with editor offers and never suggestsGetAwaiter().GetResult(). - CR0192, CR0193, CR0194 (tabled in §8.A and §8.B) — notes; the
guards are the rules' sections in Rules.md: constants by the semantic
model and a compared expression that runs nothing (CR0192); a bare
emptiness test, nothing in the branch writing the nullable, closures not
counted, a field not refilled by a call before the read (CR0193); the
invoked method declared on, and returning, a type of
System.Collections.Immutableitself, noout/refresult, the string shape yielding to CA1806 (CR0194).
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0120 | correctness | v | v | cmd.CommandText = $"SELECT … WHERE id={id}", new SqlCommand("… " + name), db.Database.ExecuteSqlRaw($"…"), Dapper Query($"…") |
note: parameterise | FR0066 | CA2100, CA3001 | |
| CR0121 | correctness | v | a SQL command whose text carries no parameter at all | note | FR0146 | — | ||
| CR0122 | correctness | v | v | Process.Start("cmd", $"/c {input}"), psi.Arguments = "… " + input |
note: ArgumentList |
FR0126 | — | |
| CR0123 | correctness | v | v | a literal matching a provider's documented key format (sk-ant-, sk-, AIza, ghp_, AKIA, xoxb-, PEM headers) |
note | FR0127 | — | |
| CR0124 | correctness | v | a credential in a const connection string on a non-loopback server |
note | FR0153 | — | ||
| CR0125 | correctness | v | v | MD5.Create(), SHA1, DES, TripleDES, RC2; ServerCertificateCustomValidationCallback = (…) => true; SecurityProtocolType.Tls11/Ssl3 |
note; editor: SHA256/SHA512, comment out or Tls12 |
FR0065 | CA5350/CA5351/CA5359/CA5364/CA5386/CA5397 | |
| CR0126 | idiom | v | new SHA256Managed(), new RNGCryptoServiceProvider() |
SHA256.Create(), RandomNumberGenerator.Create() |
FR0128 | SYSLIB0021 (warning, no fix) |
Guards.
- CR0120 — sinks are
CommandTextsetters,*Commandconstructors,FromSqlRaw/ExecuteSqlRaw/SqlQueryRaw, Dapper'sQuery*/Execute*, and helpers named for SQL; aFormattableString-typed parameter (FromSqlInterpolated,FromSql) is the safe API and never fires (typed); text followed one hop through a local. - CR0122 —
ProcessStartInfo.ArgumentListand a fixed file name never fire; a dynamically built string reachingFileName/Arguments/the two-stringStartdoes. - CR0123 — format anchoring, not entropy; a literal containing
testis a test credential and stays quiet. - CR0124 — loopback servers (
localhost,127.0.0.1,::1,(local),(localdb)\…,.) are never reported. The second shape — a literal given to a parameter, field, property, local or initializer member whose name ENDS in a credential word (password,passwd,pwd,secret,apikey,token,credential) — is quiet in test files and for placeholders, samples, short texts, names and setting keys, scheme words, prose, formats and URLs; the message never shows the literal. - CR0125 — protocols from a curated list AND from
[Obsolete]; the WebSocket handshake SHA-1 beside RFC 6455's GUID is quiet; a SHA-1 in a switch arm whose sibling constructs SHA-256 is a caller's format option; retiring a protocol changes what the wire negotiates, so it is editor-only ordrop_legacy_protocols, never granted by--api-changes. - CR0126 — zero-argument constructors only; same algorithm, so behaviour is preserved; a weak algorithm keeps its CR0125 note separately.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0140 | cosmetic | v | [SerializableAttribute] |
[Serializable] |
FR0082 | — | ||
| CR0141 | cosmetic | v | [Foo()] |
[Foo] |
FR0083 | — | ||
| CR0142 | cosmetic | [A] [B] on one line |
[A, B] |
FR0060 | — | |||
| CR0143 | cosmetic | v | @name where name is no keyword |
name |
FR0084 | — | ||
| CR0144 | cosmetic | v | else { if (c) { … } } |
else if (c) { … } |
FR0111 | — | ||
| CR0145 | idiom | v | System.Text.Json.JsonSerializer.Serialize(…) spelled six times in a file (four when three segments deep) |
using System.Text.Json; after the last using, every use shortened |
FR0147 | IDE0001 (once the using exists) | ||
| CR0146 | idiom | v | public decimal Rate(int n) => …; // monthly, non-compounding |
/// <summary>monthly, non-compounding</summary> above it |
FR0132 | — |
Guards.
- CR0140/CR0141 — the short form resolves to the same attribute class
(speculative check: an
Attribute-suffixed name can be a different type from the unsuffixed one). - CR0142 — off by default: one attribute per line is C#'s dominant style.
- CR0143 — not a reserved keyword and not a contextual keyword of the
file's language version (
fieldin C# 14 property accessors,record,var,async,nameof…), checked against the speculative re-bind. - CR0144 — the
elseblock holds exactly theifand no comments are lost. - CR0145 — thresholds
uses(6) anddeep_uses(4); the namespace is not already imported (ausing, aglobal using, or the SDK's implicit usings, read from the compilation) — that case is IDE0001's; a clash with a name the file defines or uses unqualified is a note; extension-method ambiguity and every other resolution change is caught by the speculative check, which is the guard here. - CR0146 — public declarations without XML docs; instruction comments
(
TODO,HACK,pragma-like), comments spelling code, and comments containing</&(invalid XML text) are left alone; test files quiet.
The families above are what clear C# has said since C# 8. Each version
since has closed a gap toward the functional style the tool is opinionated
for — records, exhaustive switches, list patterns, field, extension
blocks, and in C# 15 native unions — and every rule here is the rewrite a
newer level makes possible. Every one is gated on the file's effective
language version, read as a number (int LanguageVersion >= 1100), so
the analyzer pinned to Roslyn 4.14 gates C# 15 without naming it; Latest
and Preview are mapped through the host compiler's
MapSpecifiedToEffectiveVersion, so a project on <LangVersion>preview
under the .NET 11 SDK sees the C# 15 rules and one on the .NET 10 SDK does
not. Where a fix also needs a type (UnreachableException,
FrozenDictionary, System.Threading.Lock), §4.5's capability gate asks
the compilation.
Verified against Roslyn 5.12 preview (2026-09): LanguageVersion.CSharp15 = 1500 exists and Latest maps to it; the compiler parses a
UnionDeclaration as union Shape(Circle, Rect); over existing types, or
union Shape { record Circle(double R); record Rect(double W); } — not
the comma-separated case list the early write-ups show. CR0156 targets
the first form and re-verifies its syntax against the shipped compiler
before its default is decided; until then it is gated behind C# 15 and
silent everywhere else.
| Code | Cat | On | API | Pri | Needs | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|---|
| CR0147 | idiom | v | C# 11 | if (xs.Length == 0) … else if (xs.Length == 1) { var a = xs[0]; … } else … — a chain of length tests on one countable with positional reads |
xs switch { [] => …, [var a] => …, _ => … } (or the if form with list patterns) |
FR0112 (list half) | — | ||
| CR0148 | performance | v | C# 11 | Encoding.UTF8.GetBytes("literal"), Encoding.ASCII.GetBytes("literal") on a constant |
"literal"u8.ToArray(); bare "literal"u8 where a ReadOnlySpan<byte> is expected |
— | — | ||
| CR0149 | idiom | v | C# 11 | an init/set property with no initialiser that every object initialiser in the compilation sets and no constructor assigns |
required |
FR0145 (the inverse) | — | ||
| CR0150 | performance | v | v | .NET 8 | static readonly Dictionary<K,V> / HashSet<T> filled in its initialiser or static constructor and only ever read |
FrozenDictionary<K,V> / FrozenSet<T> via .ToFrozenDictionary() / .ToFrozenSet() |
FR0035 | — | |
| CR0151 | performance | v | v | C# 13 | params T[] on a method whose body only enumerates, indexes or measures the array |
params ReadOnlySpan<T> |
— | — | |
| CR0152 | performance | v | C# 13, .NET 9 | private readonly object _gate = new(); used only as a lock target |
private readonly Lock _gate = new(); |
— | — | ||
| CR0153 | idiom | v | C# 14 | a property whose private backing field is referenced only inside that property's own accessors | the field keyword, the backing field removed |
— | — | ||
| CR0154 | idiom | v | C# 14 | if (x != null) x.P = v;, if (x is not null) x[i] = v; |
x?.P = v; |
— | IDE0031 | ||
| CR0155 | idiom | v | C# 14 | a static class holding only this T-extension methods on one receiver type |
an extension(T x) { … } block |
— | — | ||
| CR0156 | idiom | v | v | C# 15 | a memberless abstract record Base; whose only derived types are sealed records in the same assembly |
union Base(Case1, Case2); with : Base dropped from each case |
FR0016, FR0022 | — | |
| CR0157 | idiom | v | C# 8, .NET 7 | a switch expression over an enum, a union or a sealed hierarchy whose discard arm throws InvalidOperationException/SwitchExpressionException/ArgumentOutOfRangeException without arguments |
throw new UnreachableException() |
— | — | ||
| CR0158 | idiom | v | C# 15 | a switch expression over a native union that lists every case and keeps a _ => arm |
note: the compiler now proves exhaustiveness, and the arm hides a missing case | — | — |
Guards.
- CR0147 — the subject is a plain identifier typed as an array,
string,List<T>,Span<T>/ReadOnlySpan<T>or any type with both aLength/Countand an indexer the compiler accepts in a list pattern (the speculative check decides); every link compares that length with==against an integer constant (0, 1, 2 …, ascending order not required); a branch readsxs[i]only foribelow its own length, each read becoming avarbinder named from the read's declaration (var a = xs[0];gives[var a]) or_; the shared switch guards of CR0002 apply; three links at least, or two with a terminalelse; CR0002 stands down on the same chain (a length is a constant comparison too — CR0147 is the better spelling and wins the overlap). - CR0148 — the argument is a compile-time constant string whose every
character is below U+0080 (so UTF-8 and ASCII agree and
u8is exact);Encoding.UTF8/Encoding.ASCIIbound to the BCL properties; abyte[]target keeps.ToArray()— the allocation stays but the transcoding goes; aReadOnlySpan<byte>target drops it; measured on the allocation axis for the span case. - CR0149 — every construction site of the type in the compilation is an
object initialiser or
withthat sets the property; no constructor of the type assigns it; no initialiser on the declaration; the type is not deserialized by the shape heuristic (a serializer constructs without initialisers);requiredis an API demand on callers, so the public shape is gated on--api-changesand the internal one on the friend check;SetsRequiredMembersconstructors are respected. Off by default (decided at M3):requiredis also a runtime demand on every deserializer of the type — System.Text.Json throws on a missing required member — and no build can prove a type is never deserialized. - CR0150 — the field is
static readonly, written exactly once (its initialiser, or a static constructor that fills it and nothing else touches it after); every other reference is a read (TryGetValue, indexer get,ContainsKey,Contains,Count, enumeration,Keys/Values); the field is private, or internal under the friend check — aDictionarytyped field is API;FrozenDictionaryresolves in the compilation; the comparer argument travels; measured on lookup throughput and on the build cost against the number of reads. - CR0151 — the array parameter is used only for
foreach,Length, indexing, or passing to aReadOnlySpan<T>/params ReadOnlySpan<T>parameter; never stored, returned, captured by a lambda, passed to an array orIEnumerable<T>parameter, or used with LINQ; the method is private/internal or--api-changesis on (aparamstype change is binary-breaking); overload resolution re-checked speculatively at every call site in the compilation. - CR0152 — the field is
private readonly objectwith anew()/new object()initialiser; every reference is the operand of alockstatement (Monitor.Enter,Wait,Pulse, passing or comparing it vetoes);System.Threading.Lockresolves; measured (the dedicated type skips the object-header lock path). - CR0153 — the backing field is private, unattributed, and referenced
only inside the getter and setter of one property of the same type —
in every part of a partial type, across files; a
nameofof the field or a string literal spelling its name anywhere in the compilation (reflection by name) vetoes (a constructor writing it vetoes — that constructor would have to target the property, which changes when the setter runs); no[ThreadStatic]/volatile; the field's initialiser moves to the property; the namefieldis not already an identifier in the type (the contextual keyword would shadow it). - CR0154 — the condition is a null test of a pure read
x(identifier or dotted read through CR0004's receiver test), the body is exactly one assignment whose target isx.P/x[i]withxthe same text, noelse; the right-hand side ofx?.P = vis not evaluated whenxis null, which is what the original did too, sovmay be anything; compound assignments (+=) included;xnot assigned inside the body. - CR0155 — off by default, v2: the class is
static, every member athis T-extension method on the same first parameter type, no fields or nested types; the block keeps every method body verbatim withthis T xbecoming the receiver; callers do not change; a public static class is API (the class name disappears from reflection and from callers who invoked the methods statically), so the api gate applies and the tool re-binds every call site. - CR0156 — the base is an
abstract record(orabstract classwith no members beyond an implicit constructor) with no members, no interfaces and no attributes; every derived type is asealed recordin the same assembly and derives from nothing else; nothing references the base as a type argument constraint or through reflection; the union syntax is the one the compilation's compiler accepts (the speculative check proves it); everyswitchover the base still compiles; the public shape is API (the base type changes kind) and gated. - CR0157 — the scrutinee's type is an enum, a native union or a
sealed hierarchy every case of which the switch lists (so the discard
is unreachable by construction); the thrown exception is
parameterless;
System.Diagnostics.UnreachableExceptionresolves; a message argument stands the fix down to a note (the message may be a contract). - CR0158 — C# 15 only; verified against the shipped compiler before its default is decided (the compiler may warn on the arm itself, in which case this rule yields to that warning id).
The families above port the F# rules and add what clear C# says. This
family is the other direction: defects a C# program can have that an F#
program cannot by construction — a for variable captured by a closure
and read after the loop moved on (F# closes over an immutable value), a
mutating call on a struct the compiler copied first (F# structs are
immutable unless spelled mutable), a rethrow that drops the inner
exception, a collection mutated under its own foreach, a token accepted
and never observed. The fixes here are the corrections, not equivalences:
a rule fixes only where the defect is
proven from the typed tree, and where the intent could go either way it
reports.
| Code | Cat | On | API | Pri | Fires on | Fix | F# | Yields to |
|---|---|---|---|---|---|---|---|---|
| CR0160 | correctness | v | v | a lambda or local function created inside a loop reads a local the loop writes (the for variable, or a local assigned in the body), and the closure outlives the iteration — stored in a collection, a field, an outer local; returned or yielded; handed to Task.Run, Task.Factory.StartNew, ThreadPool.QueueUserWorkItem, a Thread, a Timer, an event +=, or kept alive through a lazy LINQ chain that escapes |
var i1 = i; before the statement, the closure reading i1 (the per-iteration copy the author meant) |
— (immutable bindings) | — | |
| CR0161 | correctness | v | v | a call to a mutating method of a non-readonly struct on a receiver the compiler copies first: a readonly field, a property, a List<T>/IList<T> indexer, a foreach variable, an in parameter |
note: the call mutates a copy | FR0161 (the property-getter copy, the rest FS0256) | — | |
| CR0162 | correctness | v | v | new System.Threading.Timer(…) whose result is dropped or bound to a local that never leaves the method |
note: the timer is collected with its last reference and stops firing | FR0163 | — | |
| CR0163 | correctness | v | v | sem.Wait() / await sem.WaitAsync() (Semaphore.WaitOne, Mutex.WaitOne, ReaderWriterLockSlim.Enter*Lock) followed by statements and a matching Release()/ReleaseMutex()/Exit*Lock() in the same block with no try between them |
try { … } finally { sem.Release(); } |
FR0123 (the leak half) | — | |
| CR0164 | correctness | v | if (_cache == null) _cache = expr; / _cache ??= expr on a static reference-typed field outside any lock |
LazyInitializer.EnsureInitialized(ref _cache, () => expr) |
FR0162 (note only: lazy is the answer) |
— | ||
| CR0165 | correctness | v | v | catch (Exception ex) { throw new MyException("…"); } — a wrapping throw that drops the caught exception, where the wrapper has a (string, Exception) constructor |
throw new MyException("…", ex); (naming an unnamed catch ex) |
FR0160 | CA2200 | |
| CR0166 | performance | v | try { v = int.Parse(s); } catch (FormatException) { … } and try { return int.Parse(s); } catch (…) { return d; } — a parse driven by its exception, for a type with the matching TryParse |
if (!int.TryParse(s, out v)) { … } / return int.TryParse(s, out var v) ? v : d; |
FR0168 | — | ||
| CR0167 | correctness | v | a == b / a != b where both sides are float/double/Half and neither is a literal |
note: floating-point equality; compare a difference against a tolerance | — (skipped on purpose in F#) | — | ||
| CR0168 | correctness | v | a / b with two integral operands whose result lands in a double/float/decimal — a declaration, an assignment, a return, an argument |
note; editor offers (double)a / b |
FR0159 (a sweep fix there: the F# shape is an explicit conversion) | — | ||
| CR0169 | correctness | v | v | DateTime.Now/Today compared with, subtracted from or assigned beside DateTime.UtcNow (directly, or through a local, field or property set from one of them once) |
note: the two kinds differ by the machine's offset | FR0165 | — | |
| CR0170 | correctness | v | a method with a CancellationToken parameter holding a loop that awaits, sleeps or blocks on a task and never reads the token — no ThrowIfCancellationRequested, no IsCancellationRequested, no call taking it |
ct.ThrowIfCancellationRequested(); as the loop's first statement |
FR0118 (the loop half) | — | ||
| CR0171 | correctness | v | v | foreach (var x in xs) { … xs.Remove(x) … } — the enumerated collection mutated under its own enumeration (Add/Insert/Remove/RemoveAt/Clear) |
xs.RemoveAll(x => cond) when the body is exactly if (cond) xs.Remove(x); on a List<T>; otherwise a note |
FR0164 | — |
Guards:
- CR0160 — the closure is a lambda, anonymous method or local
function; the captured local is declared outside the closure and inside
the method; the loop is
for,whileordo(aforeachvariable is fresh per iteration since C# 5) or the local is assigned inside the loop body outside the closure; the closure only READS the local (a write inside it, or in any other closure of the loop, makes the shared cell the point); an outer loop's variable read from an inner loop is as captured, the copy landing right before the closure in the inner loop; the closure escapes the iteration through one of the listed channels, climbed through parentheses, casts,?., conditional expressions and lazy LINQ chains (a callee returningIEnumerable<T>/IQueryable<T>/IOrderedEnumerable<T>keeps the closure alive; one returning anything else consumed it); a closure passed to any other callee is a note, never a fix (the callee may invoke it before the next iteration); the copy takes the local's name with the first free numeric suffix, declared withvarbefore the statement holding the closure (in the loop body, at statement level — a closure in the loop condition or incrementor is a note); the same statement creating several closures over the same local shares one copy; the outer scope is not an expression tree. Outside a loop, a local assigned after the closure's creation and read by an escaped closure is a note only (late binding is sometimes meant). - CR0161 — the receiver's struct type is not
readonly struct, the method is not areadonlymember, and the method is proven to mutate: in source, it assigns a field or auto-property ofthis, calls another proven mutator onthis, or passesthisbyref; from metadata onlyMoveNext,Reset,Enter,TryEnter,Exit,Dispose(the enumerators andSpinLock). Receivers: areadonlyfield (instance or static) of the enclosing or another type, a property (any getter), an indexer whose containing type is not an array (an array element is a variable), aforeachiteration variable, aninparameter, ausingvariable. A local, an array element, arefreturn, aref/outparameter,thisand a non-readonly field are variables and never reported. TheDisposecase is reported only on aforeachvariable orinparameter (a property's disposable is the property's). - CR0162 — the constructor is
System.Threading.Timer(notSystem.Timers.Timer, which a started timer roots through the timer queue by its ownElapsedcallback — measured, it keeps firing); the expression is a statement of its own, or the initialiser of a local that is never assigned to a field, a property, an outer collection, never returned, never passed as an argument, never captured by a closure and never disposed (ausing var timeris a scoped intent). - CR0163 — the acquire is a statement of its own (
sem.Wait();,await sem.WaitAsync();,sem.Wait(ct);) with no timeout argument and no result used (if (sem.Wait(100))is a different contract); the release is a statement on the same receiver (by symbol) later in the same block; no statement between them is atrywhosefinallyreleases the same receiver; the receiver is not released anywhere else in the block (two releases mean a counting semaphore) and not re-acquired between the two; nothing between them declares a local used after the release (thetrywould scope it out — the rule moves the release only, keeping declarations outside is not attempted: such a shape is a note);Releasetakes no argument; the statements moved may containreturn/break/continue(thefinallyruns on each, which is the correction). The statements between become thetrybody, the release thefinally. - CR0164 — the field is
static, of a reference type, notvolatile, not[ThreadStatic], notreadonly; the test is== null,is null, the??=form or the older_x ?? (_x = expr)as a value; the assignment is the wholeifbody (or the??=is the whole expression of a statement or areturn); the initialising expression is provably non-null — anew, an array or collection expression, a string literal, an interpolated string, a??whose right side is one of these, or (under#nullable enable) a call whose flow state is not-null; the expression does not mention the field; neither the statement nor an ancestor is inside alock, and the enclosing method is not a static constructor (both already serialise);System.Threading.LazyInitializerresolves. The??=form is rewritten in place; theifform to a statement, keeping a followingreturn field;asreturn LazyInitializer.EnsureInitialized(…). Instance fields are not reported (a per-instance cache is usually confined). - CR0165 — the
throwis a statement directly in the catch block (or under anifin it), throwingnew T(args)where every argument is a string-typed expression (one or more) andThas an accessible constructor whose parameters are the same arguments followed by oneSystem.Exception; the caught exception (named or not) is mentioned nowhere in the arguments;Tis not the caught type re-thrown identically (throw;is CA2200's business). An unnamed catch (catch (Exception)) or a barecatchgains the nameex(first free ofex,e,exception); a barecatchbecomescatch (Exception ex). - CR0166 — the
tryblock holds exactly one statement:target = T.Parse(args);where the target is a local or field (not a property, not an indexer —outneeds a variable) orreturn T.Parse(args);;Tisint/long/short/byte/sbyte/uint/ulong/ushort/float/double/decimal/bool/char/Guid/DateTime/DateTimeOffset/TimeSpan/Enum.Parse<E>(→Enum.TryParse<E>); theTryParseoverload with the same arguments plusoutresolves (proven by the speculative bind, so aNumberStyles/IFormatProvidervariant goes through only where the framework has it); exactly one catch clause, no filter, nofinally, covering every failureTryParsewould answerfalseto:Exception/SystemExceptionalways,FormatExceptiononly for a parse that cannot overflow (bool,char,Guid,DateTime,DateTimeOffset, an enum) whose argument is not-null by flow analysis — a numeric parse undercatch (FormatException)let an overflow propagate;OverflowExceptionalone,ArgumentException,ArgumentNullExceptionare notes; the catch variable, if named, is not read (the message would be lost); for thereturnform the catch body is exactlyreturn expr;withexprpure. Any othertrywhose catch namesFormatExceptionand whose body calls aParseof the list is a note. - CR0167 — both operands' types are
float,doubleorHalf(nullable lifted included); at least one operand is computed here — arithmetic, a call, a conversion — two stored copies of one value (a tie test after>=) compare exactly; neither operand is a literal, a constant (double.NaNtests readIsNaNanyway),defaultor aMath.Round/Math.Floor/Math.Ceiling/Math.Truncatecall (whole numbers compare exactly); not inside a test method; not aswitchpattern. - CR0168 — the division's operands are both integral typed (
int,long,short,byte, their unsigned kinds, orchar), neither is a literal1, the division is not itself under a cast, and the destination isdouble/float/decimal/Half: the declared type of a local or field being initialised, the type of an assignment target, the method's return type of areturn, or the parameter type of the argument position (aparamselement type counts); aMath.Flooraround it, or the result feeding an integral variable first, is not reported. The editor offer casts the left operand to the destination type ((double)a / b); a sweep never applies it (integer division into a floating target is occasionally meant). - CR0169 — an operand chain of
==,!=,<,<=,>,>=,-,CompareTo,Equals,Subtractwhere one side derives fromDateTime.Now/DateTime.Todayand the other fromDateTime.UtcNow, "derives" meaning the expression itself, a.Date/.AddX(…)on it, or a local/field/property (in this file) whose only write is one of those; a.ToUniversalTime()/.ToLocalTime()on either side stands the rule down;DateTime.SpecifyKindandnew DateTime(…, DateTimeKind.X)make the kind explicit and stand it down. - CR0170 — the enclosing method, lambda or local function declares a
parameter of type
CancellationToken(its own parameter, not a field); the loop (for,foreach,while,do) body contains anawait, aThread.Sleep, or a block on a task (.Wait(),.Result,GetAwaiter().GetResult()) — an in-memory loop over a user call is not long by itself; neither the loop's condition nor its body nor any nested closure mentions the parameter; the loop is not nested inside another loop of the same method that observes the token (the outer check is the author's granularity) and not inside afinally; the loop body is a block (an expression-bodied loop is a note); the insertion isct.ThrowIfCancellationRequested();with the parameter's name, at the block's first statement. Iterators (yield) are included. A token parameter declared= defaultis included (the caller who passes one expects it honoured). - CR0171 — the
foreachsource is an identifier or member access (a.ToList()/.ToArray()copy is another object;d.Keys/d.Valuesenumerateditself — the key and value collections' enumerators check the owning dictionary's version — so the reference watched isd); a callxs.Add/AddRange/Insert/Remove/RemoveAt/RemoveAll/Clearon the same reference (by symbol) inside the loop body outside any nested closure, not followed bybreak/return/throwas the next statement in the same block (mutate-and-leave is the accepted idiom); the source's type isList<T>,IList<T>,ICollection<T>,Collection<T>,ObservableCollection<T>,HashSet<T>,ISet<T>,Dictionary<K,V>,IDictionary<K,V>,SortedSet<T>,Queue<T>,Stack<T>,LinkedList<T>— a concurrent collection is built for it;Dictionary/HashSet.Removeand aDictionaryindexer set on CoreLib tolerate enumeration (.NET Core 3.0+) and are quiet. The fix, only for a source typedList<T>in source or metadata: the body is exactlyif (cond) xs.Remove(x);(block or not, noelse) withxthe iteration variable andcondpure, not mentioningxs; thenxs.RemoveAll(x => cond);replaces the loop (Remove(x)removes the first element equal tox, which the enumeration reached before any duplicate — the same set of elements go).
| F# rule | Why not |
|---|---|
| FR0002, FR0009, FR0025, FR0034 (module forms), FR0059, FR0069 | No Option/Result types. Nullable<T> is already a struct, so FR0069's boxing does not exist in C#; a T? reference is a flow annotation, not a container. |
| FR0003, FR0008, FR0023, FR0090, FR0091, FR0095 | No currying, composition operator, or data-last convention. Extension methods are data-first by construction. |
| FR0005, FR0073, FR0078, FR0029, FR0149's CE half | No computation expressions; C# async state machines have no resumable-code dynamic fallback (FS3511). CR0046 is the one C# state-machine shape worth a rule. |
FR0006, FR0011, FR0087, FR0088, FR0096, FR0115, FR0129 (function) |
No active patterns; C# patterns are covered by CR0003/CR0009/CR0010. |
| FR0007 | C# has no keyword for an immutable local; a constant one is CR0172's const. Fields are IDE0044's business (readonly). |
| FR0016, FR0022, FR0072 (DU half), FR0110 (DU half) | No discriminated unions below C# 15; CR0013/CR0014 cover enums, and the C# 15 union unlocks CR0156/CR0158 (§8.I). |
| FR0013, FR0094, FR0097 | Parentheses are load-bearing in C# (IDE0047 handles the redundant ones). |
FR0024, FR0092 (the failwith half) |
No failwith; CR0069 covers the message. |
| FR0031's three-hole limit, FR0042, FR0043 | The printf path does not exist; C# interpolation lowers to a handler on .NET 6+ and to string.Format before, which CR0100/CR0101 gate on. |
| FR0057 | XML doc drift is CS1573's when docs are generated, and a convention otherwise. |
| FR0080 | Tabs are dotnet format's. |
| FR0089 | No list/tuple literal ambiguity. |
| FR0093 | C# tuples are ValueTuple already; CR0082 covers Tuple<>. |
| FR0099, FR0133, FR0135, FR0143, FR0144 | Light syntax, backtick names, literate scripts and #load/#r do not exist. |
| FR0102 | List<T> indexing is O(1); CR0026 covers the enumerable case. |
| FR0116 | No let rec … and groups. |
| FR0131, FR0158 | C# guarantees no tail calls; the loop is the right spelling. |
| FR0074 | with { A = r.A with { B = v } } is how C# spells it. |
| FR0145 | required members are a compile error when missing. |
| FR0077 | Missing interface members are a compile error with a Roslyn fix. |
Not by oversight; by the same policy that keeps FSharp.Refactor out of naming and layout:
- Naming (IDE1006, CA1707–CA1725), file and member layout (SA1xxx),
var(IDE0007/IDE0008), braces (IDE0011),this.(IDE0003), expression-bodied members (IDE0021–IDE0027), accessibility modifiers (IDE0040),readonly(IDE0044), unused parameters and variables (IDE0059/IDE0060): style, and owned by the IDE rules anddotnet format. - Method length, parameter count, cyclomatic complexity, class coupling (CA1502, CA1505, CA1506): structure metrics agents make less relevant.
ConfigureAwait(false)(CA2007): a library policy, not a defect.- Exposing
List<T>(CA1002), collection property setters (CA2227),IEnumerablereturn preferences: API design taste. - Primary constructors (IDE0290), collection expressions (IDE0300–IDE0305),
is not null(IDE0041), pattern-matching preferences (IDE0019/IDE0020/ IDE0038/IDE0078/IDE0083),switchstatement → expression (IDE0066),usingstatement → declaration (IDE0063),new()(IDE0090): Microsoft ships them with fixes; enabling them is the user's.editorconfig. async/awaitelision in general (only the exact CR0046 shape is safe),ValueTaskmisuse (CA2012 covers it),BinaryFormatter(SYSLIB0011), insecure randomness (CA5394),GC.Collect().
The fsharp-refactor contract, with the pipeline simplified by Roslyn.
Targets — X.csproj, X.cs (its project found through the nearest
solution or directory walk-up; only that file is edited), X.sln/X.slnx,
src/, "src/**/*.csproj", and a workspace directory of checkouts (each
analysed on its own into one report, paths relative to the workspace).
Flags — --dry-run, --codes, --categories, --exclude-codes, --jobs,
--framework, --max-passes, --api-changes, --no-if-defs, --report <sarif|json|html|csv>,
--baseline, --fail-on-findings, --notes [on|off|only], --format json,
--rules, --create-config, --mcp, --parse-only, --honor-suppressions,
--help. Exit codes 0 clean, 1 failure, 2 usage, 3 findings (with
--fail-on-findings).
Pipeline per target:
Microsoft.Build.Locatorregisters the SDKglobal.jsonresolves;MSBuildWorkspaceopens the solution or project. A multi-targeted project appears once per framework; passes run narrowest first. Workspace diagnostics (a project that failed to load) are printed and the project skipped, never guessed at. A C# script (.csx, the fsx twin) needs no MSBuild:Scripts.fsreads it into the adhoc workspace as a project of oneSourceCodeKind.Scriptdocument with the running runtime as its references,#rresolved against the script's directory, the runtime directory and the NuGet cache (#r "nuget: Name, Version", the newest matching version, the bestlibframework),#loadhanded to the compiler'sSourceFileResolverfor context (a loaded file is a target of its own; a directory sweep lists every loose*.csx), dotnet-script's defaultusings,ConsoleApplicationoutput so the script is a leaf. Nothing builds a script: the in-memory error count is the arbiter, and a host's globals (Args) are errors on both sides of it.- Refuse a compilation with errors (
GetDiagnostics()at error severity), as today.--parse-onlyskips MSBuild: sources come from the SDK's default globs and the csproj'sCompileitems, no references, syntax rules only, the same skew warning as the F# README. - Per pass:
CompilationWithAnalyzers(withreportSuppressedDiagnosticsso the suppression policy can see pragmas) → findings → fixes taken from the pure core → grouped per file, overlaps held for the next pass → applied bottom-up as text changes →compilation.ReplaceSyntaxTreefor every edited file → the in-memory error count must not rise. A rise bisects the pass per file: the file whose fixes raised it is put back and its fixes recorded as defects of this tool (the log line is the bug report), the rest stand. Files are written only after the pass verifies. Repeat until a pass applies nothing or--max-passes. This replaces the F# tool's per-passdotnet buildwith a check that takes seconds and is exact for C#. - The api pass (
--api-changes,api_changes = true, or a test project): cross-project fixes (CR0041, CR0069, CR0080–CR0083, CR0088) useSymbolFinder.FindReferencesAsyncover the wholeSolution, C# and VB projects alike, in one atomic edit set per finding, each touched file re-bound by the speculative check. Shipped 2026-09-20: aTextEditcarries an optionalFile(another file of the solution); theRuleContextcarries an optional reference oracle (References.fs,SymbolFinderover the solution, a VB site read-only) that the tool and the fix provider supply and the compiler leavesNone; a rule reaches the compilation's other trees without it (CR0041's callers, CR0082's spellings) and other projects through it;Guards.speculativeCheckAcrosspatches every touched tree of the compilation into one fork; the fix provider applies a set as aSolutionchange; the sweep applies each file's edits to its own document (a file reached this pass holds its own fixes to the next), verifies every touched project's error count, bisects per edit-set unit (a document's fixes with every file they reached stand or fall together), and builds the other projects touched. A cross-project fix only the oracle can see (the analyzer never reported it) becomes a finding of its own under the api pass, where the rule is on for the tree. A referencing F# project cannot be loaded byMSBuildWorkspace, so a C# project with an F# consumer keeps its public surface (PublicSurfaceHeld) unless the final build proves the consumer — the mirror of the F# tool's C#-consumer rule. - Final arbiter:
dotnet buildof every changed project in every framework, and of every project of another language that references one; a failure puts the run's fixes back file by file as unverified (never kept as pre-existing breakage) and says so. Child builds run withMSBUILDDISABLENODEREUSE=1and a bounded wait on their pipes. - Reports: SARIF 2.1.0 with the rule's help link, three lines of context,
the fix as a
fixesentry, the invocation record and a stable fingerprint (rule + file name + normalised surrounding source, the scheme of the F# tool, keycsrefContextHash/v1) so--baselineratchets identically; HTML with per-rule grouping and before/after; CSV;--format jsonon stdout. The README also documents the zero-tool CI path:dotnet build -p:ErrorLog=findings.sarifwrites the analyzer's own findings as SARIF, since the analyzers run inside the compiler. --mcp:analyzeandlist_rulesover stdio, one resident workspace, the compilation cache warm across calls.
Held-back accounting — every gate (scope, capability, speculative
check, a shadowed Microsoft rule being on, a pragma under a no-correctness
policy) counts what it held and the run prints the counts with the key or
flag that would release them.
The C# extension (and C# Dev Kit) hosts Roslyn as a language server that loads analyzers from the project. The extension therefore ships no language client; it does three things:
- Wire, with consent. On first activation it offers to make the bundled
analyzers apply machine-wide by writing an MSBuild user extension props:
%LOCALAPPDATA%\Microsoft\MSBuild\Current\Imports\Microsoft.Common.props\ImportBefore\CSharp.Refactor.props(the$(MSBuildUserExtensionsPath)hook MSBuild imports for every project) containing an<Analyzer Include="…/CSharp.Refactor.Analyzers.dll"/>item underCondition="'$(Language)' == 'C#' and '$(CSharpRefactorDisable)' != 'true'". Every project the machine opens or builds then runs the analyzers: in the VS Code language server, in Visual Studio, and indotnet build(asInfodiagnostics, invisible at normal verbosity). Decline and nothing is written;Wire/Removecommands re-offer and undo, andStatusreports the wiring, the extension and analyzer versions, the C# extension's server version and whether the tool is installed. The per-project alternative —Add to this projectwrites aPackageReferencewithPrivateAssets="all"— is for teams that want the analyzers in source control. - Run the tool.
Run on this workspace(report-only / apply / apply with--api-changes),Write a SARIF report,Review advisory notes as a page,Create or open the configuration— the F# extension's commands, in the integrated terminal, offering to install the tool when missing. - Nothing else. Squiggles, light bulbs and fix-all come from Roslyn.
A VSIX whose payload is the analyzer assembly with FSharp.Core.dll,
declared as <Asset Type="Microsoft.VisualStudio.Analyzer"> (the diagnostics)
and <Asset Type="Microsoft.VisualStudio.MefComponent"> (the code-fix
providers), so every C# project opened in the IDE gets the light bulbs with
no project change and no effect on builds. The Tools > CSharp.Refactor menu
drives the tool exactly as the F# VSIX does (the command table must live
inside a managed .resources set — EmbedCto.ps1 and the checklist in the
F# VSIX README apply verbatim). There is no error tagger, no suggested-actions
source, no LSP client: Roslyn renders everything.
VS 2026's Roslyn runs out of process; VSIX analyzer assets are forwarded to
it, but this is the M0 spike's job to prove on 18.x. Fallback if it fails:
the same ImportBefore props the VS Code extension writes, which VS honours
through MSBuild.
A PackageReference to the NuGet package. Nothing to build.
- Unit tests are the F# side's shape: a string-literal input, compiled
against reference assemblies (
Basic.Reference.Assembliesfor .NET 10 and for netstandard2.0, so capability gates are tested from both sides), the rule run as a pure function, the suggestions asserted, every fix applied as text, the result recompiled: no new error, and for exactness-claiming rules an identical diagnostic set. One test per shape and one per guard; the stand-down cases are the ones that matter. - Host tests drive the real
DiagnosticAnalyzerthroughCompilationWithAnalyzers: descriptor completeness,.editorconfigreading, the yields-to gate, generated-code skipping, pragma handling and the suppression policy, the deep-stack worker. - Property tests (
tests/CSharp.Refactor.PropertyTests, FsCheck): a generated program — a class of members, one shape per rule, 121 of the 124 rules reached (CR0017 is CR0160's wherever both read a shape; CR0156/CR0158 need C# 15) — under the invariants every rule promises: every fix compiles, no rule throws on damaged text, fixes reach a fixed point, the boolean rewrites keep the truth table. Where a wrong rewrite would compile, a shape carries a decoy that makes it fail to (an[Obsolete(error)]FormattableStringoverload for CR0100/CR0101, a tuple handed toobjectfor CR0082). The conventions of real files are properties too:#regions, a#ifand a comment inside a member, CRLF, tabs, a#pragma— every fix compiles and leaves what was there; and the language ladder — at every version from C# 7.3 to 13, a fix uses no syntax newer than the file's. Each runs over random programs and, deterministically, over every shape alone. The cross-cutting conditions the F# suite tries rule by rule (shadowing, reflection andnameof, expression trees,dynamic,unsafe, partial types across files, interface and override members, generated files, a framework lacking the type a fix introduces) are the example suite'sCrossCuttingTests. The 2026-09-20 pass that built this found and fixed: CR0084'sreadonlyoffer on a method-written field, CR0109 hoisting a pattern the engine rejects, CR0047 spellingLockandnew()below their versions, CR0009'sorpattern below C# 9 and a bare LF into a CRLF file, CR0029 fusing inside an expression tree, CR0153 blind to a partial type's other file and to reflection by name, and the tool rewriting files with an<auto-generated>header. - Catalog tests keep
Rules.mdcomplete: every code has a row and a section; category, default, API and priority match the catalog; every F# twin named exists in FSharp.Refactor'sRules.md. - PerfClaims: BenchmarkDotNet on .NET 10, one pair per claim, the contract of §5.8; losing shapes stay labelled NOT emitted; a flapping gate is isolated in its own process before it is called noise.
- Sample project:
tests/Sampleis C# the sweep must leave with zero findings and no diff (the analyzers are F#, so the dog-food run is over the sample and the tool's own C# test fixtures, not over the analyzers). - IDE smoke: the VS experimental instance recipe from the F# VSIX
(touch the
configurationchangedmarker, watch the log, stop only thatdevenv), and VS Code with the C# extension on a fixture workspace.
M0 is one week of spikes, each with a pass/fail:
- F# analyzer in three hosts. A two-rule analyzer (one parse-only, one
typed, one fix) packed with FSharp.Core loads and fires under
dotnet build, in VS 2026 (VSIX asset ANDPackageReference), in VS Code's C# extension, and in Rider. Fail → the fallback is a C# adapter assembly that exports the analyzer and fix provider and calls the F# core, keeping the rules in F#. 2026-09-19, partly verified: the spike analyzer (CR0090, CR0103) built against Roslyn 4.14 on netstandard2.0 with FSharp.Core 9.0.303 beside it fires underdotnet buildof the .NET 10 SDK both as an<Analyzer>item and as aPackageReferencefrom the packed.nupkg(nothing leaks into the consumer'sbin), Info findings reach-p:ErrorLogSARIF, an.editorconfigseverity override is honoured, and the F# fix provider registers both code actions and applies them through anAdhocWorkspace(tests/CSharp.Refactor.Tests/HostTests.fs). Later the same day: the VS Code extension (bundled analyzers wired through the MSBuild userImportBeforeprops) and the VS 2026 VSIX (analyzer + MEF assets, no package code) both show the hints and fixes in the IDE. Rider untried. - VS 2026 out-of-process analyzers from a VSIX asset. Passed
2026-09-19 on VS 18.10 Professional in the Exp instance. One packaging
trap:
[Content_Types].xmlmust list every part's extension, including thejsonof the v3 servicing files written after the payload was staged, or the installer says "not a valid VSIX package". - Roslyn pin. The analyzer built against 4.14 runs inside the 5.x host over a C# 14 file without throwing; unknown kinds are opaque.
- Editor latency. The memoised index over a 10k-line file stays under the per-keystroke budget the C# extension allows analyzers; measure with every v1 rule on.
MSBuildWorkspaceloading across SDK pins,global.json,Directory.Build.propsand multi-targeting; workspace failure diagnostics surfaced, never swallowed.- Speculative check cost — one file re-bind per candidate finding; if it dominates on files with hundreds of findings, batch candidates per file into one re-bind.
| Deliverable | |
|---|---|
| M0 | The spikes of §14; repository skeleton; Directory.Build.props; catalog module with the 101 descriptors; Rules.md generated from it. |
| M1 | Infrastructure done 2026-09-19: tool with reports, baseline, suppression policy, --create-config, MCP, in-memory verification and final build; Rules.md kept by tests; CI; both extensions with the tool commands. Open: shared guards (isPureExpression, callsOnlyCore, speculative check, comment/directive guards, Scope/Visibility, Configuration); families A and H (the parse-only and simplest typed rules); tool in --dry-run with reports; unit and host tests. |
| M2 | Families B, C, D; the apply loop with in-memory verification, final build, held-back accounting, MCP; PerfClaims with every performance claim of those families; CR0028/CR0022 defaults decided. |
| M3 | Rules done 2026-09-20: families E, F, G and the language ladder I (§8.I, C# 11–15 gates), then family J (§8.J, the defects F# has no room for — CR0160–CR0171, 2026-09-20), 124 rules in the catalog; the api pass as the tool sees it (complete project graph, referenced executables not leaves, foreign consumers hold the surface, dependents verified and rolled back). Done 2026-09-20: cross-project FindReferences edit sets (step 4 of §11), C# scripts (.csx). Done 2026-09-20: the VS extension's Tools menu (the VS Code commands in Visual Studio). Open: NuGet, VSIX and Marketplace publishing scripts; Rider untried. |
| M4 | Corpus sweep over every C# checkout under C:\git; category and default decisions from the counts (§5.9); CR0088 editor-only; 0.1.0, 0.1.1 with the test suite brought toward the F# side's depth, 0.1.2 with the VS Tools menu. |