Skip to content

Tooling and Enforcement

Rule prefix: TOOL · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID

Home · Rule index · Naming cheat sheet

This chapter covers how the four files in config/ work and how to adopt, extend and enforce them. config/.editorconfig holds the naming rules, formatting options and analyzer severities. config/Directory.Build.props holds the MSBuild settings that make the IDE rules run in dotnet build and make every build, local and CI, fail on warnings. config/global.json pins the .NET SDK that the analyzers and the language version come from. config/stylecop.json holds the settings for StyleCop Analyzers, which ship disabled. The style rules themselves are on pages 01 to 14 and on page 16; this chapter covers how they are checked, how to silence a finding, and which rules only a reviewer can check. The build behaviour described in this chapter is that of the .NET 10 SDK (10.0.300).

Severity model. DO and DO NOT rules ship at warning, CONSIDER and AVOID rules at suggestion (rule levels). A warning fails every build, local and CI, because TreatWarningsAsErrors is always on (TOOL-014). AnalysisLevel = latest-recommended also turns the Recommended code-quality rules that have no tagged line in the .editorconfig into warnings (about 80 on SDK 10.0.300, for example CA1861, CA1869 and CA2208), and those fail the build too; to change one, put a per-ID dotnet_diagnostic.<ID>.severity line in a nested .editorconfig above the projects (for example src/.editorconfig) or in a repository .globalconfig, not under an unrelated rule tag in the copied file (TOOL-010). TreatWarningsAsErrors raises compiler, analyzer and NuGet warnings, not MSBuild (MSB) warnings. The naming rule of NAM-216 ships at none, so the build does not report it. A few diagnostics ship at suggestion although their rule is DO or DO NOT-level: CA2007, which would flood application and test projects and so reports only for library output (ASYNC-013); CA1031, CA1063 and CA1816, because process boundaries legitimately catch Exception and the dispose pattern cannot be judged case by case (ERR-012, ERR-021); and CA1034, which reports a public C# 14 extension(...) block as a visible nested type, so a warning would fail every correct extension-member example. When severities conflict, the per-ID line dotnet_diagnostic.<ID>.severity beats a category line (dotnet_analyzer_diagnostic.category-<Category>.severity), and a category line beats the global line (dotnet_analyzer_diagnostic.severity). Three kinds of rule never fail dotnet build: manual rules, IDE-only diagnostics such as IDE0003 and IDE0049 that the build never reports, and IDE options that have no EditorConfig key. The IDE-only diagnostics still fail CI through the dotnet format style step (TOOL-015); manual rules and IDE options are checked in review.

Rule index

Each row summarizes one rule of this chapter; the sections that follow give the examples and reasons.

ID Level Rule Enforced
TOOL-010 DO copy config/.editorconfig to the repository root with root = true and put project-specific overrides in .editorconfig files nested below it, never in edited copies of the root file. Manual
TOOL-011 DO write code-style option values without a :severity suffix and set each diagnostic's severity once, with dotnet_diagnostic.<ID>.severity. Manual
TOOL-012 DO set dotnet_diagnostic.IDE1006.severity = warning whenever the file defines naming rules, because a naming rule's own severity does not make it fire in dotnet build. Manual
TOOL-013 DO add a resharper_* key with the same value next to every Roslyn key that the JetBrains documentation does not list as read, such as csharp_style_namespace_declarations, csharp_style_implicit_object_creation_when_type_is_apparent, csharp_prefer_simple_default_expression and the expression-body options for operators, indexers, local functions and lambdas. Manual
TOOL-014 DO set EnforceCodeStyleInBuild, AnalysisLevel = latest-recommended, LangVersion = latest, Nullable = enable, ImplicitUsings = enable and GenerateDocumentationFile = true in Directory.Build.props, set TreatWarningsAsErrors to true on every build with only NU1900 and NU1801 kept as warnings, and pin the SDK in a global.json next to it. Manual
TOOL-015 DO run dotnet format whitespace --verify-no-changes and dotnet format style --verify-no-changes --report <dir> on every pull request, and fail the pipeline when either reports a change other than the IMPORTS using order. Manual
TOOL-016 DO keep the StyleCop.Analyzers package reference commented out until a stable release supports C# 14, and keep the SA rules that contradict this guide (SA1101, SA1122, SA1200, SA1208, SA1216, SA1309, SA1413, SA1600-SA1602, SA1611, SA1633, SA1649) at none. Manual
TOOL-017 DO suppress a diagnostic only on the narrowest scope, with #pragma warning disable <ID> and a matching restore, or with [SuppressMessage] that sets Justification, and never by lowering a severity for the whole repository to hide one finding. Manual
TOOL-018 DO check every changed file against the rules in the "Manual review only" table, because no build diagnostic enforces them. Manual
TOOL-019 DO keep the security analyzers listed in the # security-baseline block at warning (suggestion for the noisy ones), each on its own dotnet_diagnostic line, and raise individual IDs to error in a project once it has no findings for them. Manual
TOOL-020 DO reference analyzer packages with PrivateAssets="all" and pin their versions in Directory.Packages.props with central package management. Manual
TOOL-021 DO put a # <RULE-ID>[, <RULE-ID>] comment line above each property, keep untagged lines only in the header, # shared and # security-baseline blocks, and never write a comment after a value on the same line. Manual
TOOL-022 DO turn on reading settings from EditorConfig for both code style and inspections, and leave "Read code style from StyleCop files" off. Manual

Configuration files

These rules cover where the shipped files go and how each one is set.

TOOL-010

DO copy config/.editorconfig to the repository root with root = true and put project-specific overrides in .editorconfig files nested below it, never in edited copies of the root file.

✅ Correct — shared files at the repository root, overrides in a nested file

Contoso.Orders/
  .editorconfig            # copied from config/.editorconfig, contains root = true
  Directory.Build.props    # copied from config/Directory.Build.props
  global.json              # copied from config/global.json
  stylecop.json            # copied from config/stylecop.json
  Contoso.Orders.sln
  src/
    Legacy/
      .editorconfig        # overrides only, no root = true

✅ Correct — the nested file lists only what differs

[*.cs]
dotnet_diagnostic.IDE0055.severity = suggestion

❌ Incorrect — the file stays in config/ and never reaches the code

Contoso.Orders/
  config/
    .editorconfig          # Wrong: an .editorconfig applies only to files at or below its own folder
  Contoso.Orders.sln
  src/

❌ Incorrect — a second root file cuts off the shared settings

# src/Legacy/.editorconfig
# Wrong: root = true stops the search for parent files, so nothing from the repository root applies below src/Legacy.
root = true

[*.cs]
dotnet_diagnostic.IDE0055.severity = suggestion

Why: The file nearest to a source file wins, and root = true stops the search above it. The root copy therefore supplies the shared settings and a nested file lists only the differences. A root copy that has been edited in place can no longer be compared with config/.editorconfig when this guide changes. The file lives under config/ because its [*] section applies to every file type, Markdown included; in the folder that holds the guide pages it would also govern those pages.

Exceptions: In your repository the [*] section also applies to Markdown and other non-C# files: it trims trailing whitespace and sets max_line_length for every file type. trim_trailing_whitespace = true removes the two trailing spaces that Markdown uses as a hard line break; add a nested .editorconfig with a [*.md] section that sets trim_trailing_whitespace = false where that matters. The shipped file does not set line endings; leave them to an optional .gitattributes file with * text=auto. A repository that already has a root .editorconfig moves its project-specific lines into nested files first, then replaces the root file with the shipped copy. The test-file section [{**.Tests/**.cs,tests/**.cs}] applies only to projects named <Project>.Tests or placed under a tests folder (NAM-036); do not rewrite the glob, because the form [{**/*.Tests/**,**/tests/**}/*.cs] does not match the test files and the relaxation never applies.

Scope: Repositories that adopt this guide · Enforced: Manual · Sources: MS-CFGFILES, MS-CONV, RS-EDITORCONFIG

TOOL-011

DO write code-style option values without a :severity suffix and set each diagnostic's severity once, with dotnet_diagnostic.<ID>.severity.

✅ Correct — the option has a value, the severity has its own line

# FMT-060
csharp_style_namespace_declarations = file_scoped
# FMT-060
dotnet_diagnostic.IDE0161.severity = warning

❌ Incorrect — the suffix sets a second severity for the same diagnostic

# FMT-060
# Wrong: the :warning suffix duplicates the severity of the per-ID line and can drift from it.
csharp_style_namespace_declarations = file_scoped:warning

Why: dotnet build honours the suffix, per option: file_scoped:warning reports IDE0161 as a warning and file_scoped:error as an error. A dotnet_diagnostic.IDE0161.severity line overrides the suffix, so a file that has both has two severities for one diagnostic and the suffix value is dead text. No diagnostic flags the suffix, so the single form is a convention that reviewers keep. ReSharper switches its Roslyn-style "evident type" logic on only when the suffix is present, so the shipped file sets resharper_csharp_use_roslyn_logic_for_evident_types = true explicitly.

Exceptions: A misspelled key or an invalid option value is dropped without any message; only an invalid severity word (for example loud) produces the warning InvalidSeverityInAnalyzerConfig. After you edit the file, build a scratch project and check that the expected diagnostic appears (see Maintaining this guide).

Scope: Every .editorconfig line that sets a code-style option or a severity · Enforced: Manual · Sources: MS-IDE-LANG, MS-CFG

TOOL-012

DO set dotnet_diagnostic.IDE1006.severity = warning whenever the file defines naming rules, because a naming rule's own severity does not make it fire in dotnet build.

✅ Correct — the naming rule and the IDE1006 line (excerpt without tag lines)

dotnet_diagnostic.IDE1006.severity = warning
dotnet_naming_style.underscore_camel_case.required_prefix = _
dotnet_naming_style.underscore_camel_case.capitalization = camel_case
dotnet_naming_rule.nam_200_private_fields.severity = warning
dotnet_naming_rule.nam_200_private_fields.style = underscore_camel_case
dotnet_naming_rule.nam_200_private_fields.symbols = nam_200_private_fields
dotnet_naming_symbols.nam_200_private_fields.applicable_accessibilities = private, internal, private_protected
dotnet_naming_symbols.nam_200_private_fields.applicable_kinds = field

❌ Incorrect — the rule's own severity is the only severity

dotnet_naming_style.underscore_camel_case.required_prefix = _
dotnet_naming_style.underscore_camel_case.capitalization = camel_case
# Wrong: this severity alone does not make the rule fire in dotnet build, and no IDE1006 line exists, so the build reports nothing.
dotnet_naming_rule.nam_200_private_fields.severity = warning
dotnet_naming_rule.nam_200_private_fields.style = underscore_camel_case
dotnet_naming_rule.nam_200_private_fields.symbols = nam_200_private_fields
dotnet_naming_symbols.nam_200_private_fields.applicable_accessibilities = private, internal, private_protected
dotnet_naming_symbols.nam_200_private_fields.applicable_kinds = field

Why: IDE1006 is the diagnostic behind every naming rule. A method named bad_method against a PascalCase rule produces no build output until dotnet_diagnostic.IDE1006.severity = warning is added; the build then reports IDE1006 with a message that names the expected prefix or casing, such as Missing prefix: '_'. The line has no effect without EnforceCodeStyleInBuild (TOOL-014): with it set to false the same file produces no IDE1006. Nothing reports a missing IDE1006 line, so a naming rule without it silently checks nothing in CI. The shipped file carries the line once, in its # shared block.

Exceptions: A naming rule whose own severity is none stays off. The shipped test-file section does this for the Async suffix rule (dotnet_naming_rule.nam_131_async_methods.severity = none).

Scope: Every naming rule in .editorconfig · Enforced: Manual · Config: dotnet_diagnostic.IDE1006.severity · Sources: MS-IDE-NAMING, MS-CAOV

TOOL-013

DO add a resharper_* key with the same value next to every Roslyn key that the JetBrains documentation does not list as read, such as csharp_style_namespace_declarations, csharp_style_implicit_object_creation_when_type_is_apparent, csharp_prefer_simple_default_expression and the expression-body options for operators, indexers, local functions and lambdas.

✅ Correct — the Roslyn key and its resharper_* twin agree

csharp_style_namespace_declarations = file_scoped
resharper_csharp_namespace_body = file_scoped
dotnet_naming_style.underscore_camel_case.required_prefix = _
dotnet_naming_style.underscore_camel_case.capitalization = camel_case
resharper_csharp_naming_rule.private_static_fields = _+aaBb

❌ Incorrect — only the Roslyn key

# Wrong: no resharper_csharp_namespace_body twin, so ReSharper and Rider may apply their own namespace style instead of this value.
csharp_style_namespace_declarations = file_scoped

❌ Incorrect — a twin with a different value

csharp_style_namespace_declarations = file_scoped
# Wrong: the twin disagrees with the Roslyn key, so the build and the editor report different results.
resharper_csharp_namespace_body = block_scoped

Why: JetBrains documents a fixed list of Roslyn keys that ReSharper and Rider read from .editorconfig. Keys outside the list have no documented mapping. The list does not include csharp_style_namespace_declarations, csharp_style_implicit_object_creation_when_type_is_apparent, csharp_prefer_simple_default_expression, the expression-body options for operators, indexers, local functions and lambdas, or csharp_indent_case_contents. The shipped file adds a twin for these, for example resharper_csharp_namespace_body and resharper_csharp_local_function_body, and also one for constructor bodies (resharper_csharp_constructor_or_destructor_body); a twin for a key that ReSharper does read is harmless. Naming has the same gap: JetBrains does not document how required_prefix and required_modifiers map to ReSharper naming rules, nor which of dotnet_naming_rule.* and resharper_csharp_naming_rule.* wins when both exist, so the shipped file contains both and they must agree. The value _+aaBb follows the documented prefix+style grammar. underscore_camel_case and camel_case are EditorConfig style identifiers, not C# names; the C# names they produce are _orderCount and orderCount, never _order_count or orderCount_s (NAM-016). The two dotnet_naming_style.*.word_separator = _ lines in the shipped file (NAM-016) have no resharper_* twin; the ReSharper counterpart is the aaBb style token.

Scope: Settings that ReSharper and Rider read from .editorconfig · Enforced: Manual · Sources: RS-EDITORCONFIG, RD-EDITORCONFIG, RS-SYNTAX, RD-NAMING

TOOL-014

DO set EnforceCodeStyleInBuild, AnalysisLevel = latest-recommended, LangVersion = latest, Nullable = enable, ImplicitUsings = enable and GenerateDocumentationFile = true in Directory.Build.props, set TreatWarningsAsErrors to true on every build with only NU1900 and NU1801 kept as warnings, and pin the SDK in a global.json next to it.

✅ Correct — the shipped Directory.Build.props (comments removed)

<Project>
  <PropertyGroup Label="Language">
    <LangVersion>latest</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <PropertyGroup Label="Analysis">
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <RunAnalyzers>true</RunAnalyzers>
    <RunAnalyzersDuringBuild>true</RunAnalyzersDuringBuild>
    <EnableNETAnalyzers>true</EnableNETAnalyzers>
    <CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
  </PropertyGroup>
  <PropertyGroup Label="Documentation">
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>
  <PropertyGroup Label="Warnings as errors">
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <WarningsNotAsErrors>$(WarningsNotAsErrors);NU1900;NU1801</WarningsNotAsErrors>
  </PropertyGroup>
  <PropertyGroup Label="NuGet audit">
    <NuGetAudit>true</NuGetAudit>
    <NuGetAuditMode>all</NuGetAuditMode>
    <NuGetAuditLevel>low</NuGetAuditLevel>
  </PropertyGroup>
</Project>

✅ Correct — the shipped global.json

{
  "sdk": {
    "version": "10.0.300",
    "rollForward": "latestPatch",
    "allowPrerelease": false
  }
}

❌ Incorrect — warnings are errors only on the build server

<PropertyGroup Condition="'$(CI)' == 'true'">
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <!-- Wrong: a local build passes with warnings that then fail the pipeline. -->
</PropertyGroup>

❌ Incorrect — a vulnerability warning is hidden instead of accepted

<PropertyGroup>
  <NuGetAudit>false</NuGetAudit> <!-- Wrong: switches off the whole audit, so no advisory is ever reported. -->
  <NoWarn>$(NoWarn);NU1903</NoWarn> <!-- Wrong: hides every high-severity advisory with no reason recorded. -->
</PropertyGroup>

❌ Incorrect — the SDK may jump to a newer major version

{
  "sdk": {
    "version": "10.0.300",
    "rollForward": "latestMajor" // Wrong: any newer installed SDK is chosen, so the analyzers and the C# version move with the machine.
  }
}

❌ Incorrect — the IDE rules never run in the build

<PropertyGroup>
  <!-- Wrong: EnforceCodeStyleInBuild is missing, so no IDE rule fires in dotnet build. -->
  <!-- Wrong: GenerateDocumentationFile is missing, so IDE0005 never fires in dotnet build. -->
  <Nullable>enable</Nullable>
</PropertyGroup>

Why: Without EnforceCodeStyleInBuild the severities in .editorconfig serve only the editor. IDE0005 (unnecessary using) additionally needs GenerateDocumentationFile: without it the build prints the warning EnableGenerateDocumentationFile instead of reporting IDE0005. The side effect is CS1591 on every undocumented public member; the shipped .editorconfig sets it to none (DOC-023), and a public library opts in with dotnet_diagnostic.CS1591.severity = warning in a nested .editorconfig, as a comment in Directory.Build.props explains. AnalysisLevel = latest-recommended turns on the Recommended mode of the code analysis rules of the SDK in use, and LangVersion = latest selects the highest C# version that the compiler running the build supports. Both follow the SDK, so the SDK is fixed in global.json: with the pin at 10.0.300 they resolve to the rules and the C# 14 of that SDK. The rule set changes when the pin is raised or when a newer 10.0.3xx SDK is installed; patches fix analyzers but add no new rule sets, so use the same SDK patch on build agents and developer machines. Visual Studio's bundled compiler can resolve latest to a newer C# version than the CLI on the pinned SDK, so CI is the reference: a syntax error that only the IDE accepts or rejects surfaces there. A per-ID line in .editorconfig still wins over the analysis level. TreatWarningsAsErrors is on for every build, not only the pipeline: dotnet build, test, run and watch all fail on a warning, so a finding never reaches the repository because it passed on a laptop and failed later. It raises compiler, analyzer and NuGet warnings, not MSBuild (MSB) warnings. A condition on the property (a CI variable such as CI, TF_BUILD or ContinuousIntegrationBuild) would give each machine its own result, and a pipeline that does not set the variable would silently stop failing.

The NuGet audit reports through warnings, and under TreatWarningsAsErrors those warnings are errors. NU1901 to NU1904 (a package with a known vulnerability, low to critical) and NU1905 (an audit source that has no vulnerability data) stay errors, so a newly published advisory stops the build until it is fixed or accepted. NU1900 (vulnerability data could not be fetched) and NU1801 (a package source could not be reached) stay warnings, because an offline machine or a feed outage would otherwise stop every build. The cost is that the audit fails open: when the data cannot be fetched, the build passes without a check. The NuGet audit documentation (MS-NUGET-AUDIT) describes these codes and the audit in CI. Close the gap on the build server in one of two ways. A step that lists vulnerable packages (dotnet list package --vulnerable --include-transitive) reports them but does not fail a build by itself, so a step that must fail has to check its output. Or the CI build passes -p:WarningsNotAsErrors=NU1801, which replaces the build command rather than adding a step: a global property replaces the whole value in Directory.Build.props, so NU1900 becomes an error on CI and only NU1801 stays a warning, and the shipped files need no extra code, but a repository that lists its own codes in WarningsNotAsErrors repeats them in the CI value, separated by MSBuild's escaped semicolon (-p:WarningsNotAsErrors=NU1801%3B<codes your projects already list>). A host that runs the step as a batch file (an Azure Pipelines script: step on Windows, a GitHub Actions step with shell: cmd) needs %%3B instead, or the step runs in pwsh or bash. Never repeat NU1900 to NU1905 there. NU1900 is raised during restore, so a pipeline with a separate dotnet restore step passes both -p:TreatWarningsAsErrors=true and the WarningsNotAsErrors value on that step too. The shipped Directory.Build.props sets NuGetAudit, NuGetAuditMode and NuGetAuditLevel, so an agent or pipeline variable cannot switch the audit off or narrow it. It also sets RunAnalyzers, RunAnalyzersDuringBuild, EnableNETAnalyzers and CodeAnalysisTreatWarningsAsErrors to true, so an agent or pipeline variable cannot switch the analyzers off or keep CA findings as warnings. Fail the CI job when NoWarn or WarningsNotAsErrors is defined as a pipeline or environment variable, or when a Directory.Build.rsp or *.user file is tracked in the repository, and never override NoWarn with -p, because that drops the SDK's own codes. NU1801 does not stop a restore, so a repository with more than one package feed uses Package Source Mapping; otherwise an unreachable feed can hide a package that another feed then supplies. To accept an advisory, add a NuGetAuditSuppress item for its URL and record the reason next to it. Never put NU1900 to NU1905 in NoWarn, neither as the project property nor as NoWarn metadata on a PackageReference, and never set NuGetAudit to false, because both hide advisories that were never reviewed.

global.json selects the SDK for every dotnet command that starts below it. With rollForward set to latestPatch and allowPrerelease set to false, the SDK is the newest installed 10.0.3xx release at or above 10.0.300, and never a preview. When no such SDK is installed, for example a build agent with only 10.0.2xx or only 11.0, every build, restore and test command fails with the message "A compatible .NET SDK was not found". Make CI follow the file instead of a floating image: actions/setup-dotnet with global-json-file, Azure Pipelines UseDotNet@2 with useGlobalJson, and SDK container image tags in the 10.0.3xx band. An image that tracks the newest 10.0 band can carry a 10.0.4xx SDK, which latestPatch rejects. There are two fixes: install an SDK from the 10.0.3xx band (dotnet --list-sdks shows what is installed), or raise the pin. To raise it, install the newer SDK, change sdk.version to its full version number (a range, 10.0 and a wildcard are invalid), build, fix the findings that the new rules report in the same change, and update the build agents to match. The pin is a floor inside its feature band, not a promise of the newest SDK: raise it with each servicing cycle, and when a new feature band ships, so that SDK fixes reach the build and the analyzers do not fall behind.

Adopting in an existing repository. A repository that already builds may report warnings that were never errors before: NU1510, NU1603, NU1608, NU1701, CS0618 and SYSLIB obsolescence warnings among them. Under TreatWarningsAsErrors each one stops the build. Do not switch the property off to get a first green build. NU1510 (a package reference that is not needed): remove the reference, or condition the PackageReference on the target frameworks that still need it. NU1603, NU1608 and NU1701: fix the cause first; where it stays, set NoWarn as metadata on the direct PackageReference that brings the package in, with an XML comment that gives the reason. Only these three codes are muted this way; any other NuGet warning is fixed at its cause (for example NU1507: add Package Source Mapping). For NU1603 (the requested version was not found and a higher one was used), fix the version, and in a repository with several feeds check Package Source Mapping before muting it. CS0618 and SYSLIB obsolescence warnings: fix the call, or suppress it with a reason (TOOL-017).

Exceptions: AnalysisLevelSecurity is not set (see TOOL-019). NU1905 stays an error: fix an audit source that has no vulnerability data instead of listing the code in WarningsNotAsErrors. Roll back one local run with the command-line property -p:TreatWarningsAsErrors=false, which overrides the file and also turns NU1901 to NU1905 into warnings, so it is for a single local run only and never for CI. For the inner loop (F5 in Visual Studio, Rider, dotnet build and dotnet watch), a git-ignored <Project>.csproj.user file can set TreatWarningsAsErrors to false for that project: a plain <Project> element with one PropertyGroup. MSBuild imports it after Directory.Build.props, there is one per project (Visual Studio may already have created it), and the standard Visual Studio .gitignore ignores *.user. Like the -p rollback, it also turns NU1901 to NU1905 into warnings on that machine. Every restore, build, test, pack and publish command on CI passes -p:TreatWarningsAsErrors=true: a global property beats a project or .user value, so a stray .user file cannot switch off TreatWarningsAsErrors on CI, and an environment variable is no substitute. The -p rollback is a command option and is not stored; only the .user file is kept out of the repository. MSBuild reads only the nearest Directory.Build.props, so a solution that has its own file merges these properties into it.

Scope: Every project in the repository, through Directory.Build.props and global.json · Enforced: Manual · Sources: MS-CAOV, MS-MSBUILD, MS-GLOBALJSON, MS-NUGET-AUDIT, MS-NUGET-PSM

TOOL-015

DO run dotnet format whitespace --verify-no-changes and dotnet format style --verify-no-changes --report <dir> on every pull request, and fail the pipeline when either reports a change other than the IMPORTS using order.

✅ Correct — the build first, then the whitespace check and the style check as the next steps of the same job

dotnet build Contoso.Orders.sln --configuration Release -p:TreatWarningsAsErrors=true
dotnet format whitespace Contoso.Orders.sln --no-restore --verify-no-changes
if ($LASTEXITCODE -ne 0) { exit 1 }

Remove-Item artifacts/format -Recurse -Force -ErrorAction SilentlyContinue
# Exit code 2 means changes were found, which includes IMPORTS alone (checked in review, FMT-062).
dotnet format style Contoso.Orders.sln --no-restore --verify-no-changes --report artifacts/format
$styleExit = $LASTEXITCODE
if ($styleExit -ne 0 -and $styleExit -ne 2) { "dotnet format style failed with exit code $styleExit"; exit 1 }
$reportPath = 'artifacts/format/format-report.json'
if (-not (Test-Path $reportPath -PathType Leaf)) { "$reportPath was not written"; exit 1 }
$json = Get-Content $reportPath -Raw -ErrorAction Stop
if ([string]::IsNullOrWhiteSpace($json)) { "$reportPath is empty"; exit 1 }
$report = $json | ConvertFrom-Json -ErrorAction Stop
$failed = $false
foreach ($document in $report) {
    foreach ($change in $document.FileChanges) {
        if ($change.DiagnosticId -ne 'IMPORTS') {
            "$($document.FilePath)($($change.LineNumber),$($change.CharNumber)): $($change.FormatDescription)"
            $failed = $true
        }
    }
}
if ($failed) { exit 1 }
exit 0

❌ Incorrect — the style step runs without the report filter

dotnet format style Contoso.Orders.sln --verify-no-changes # Wrong: the exit code is 2 for IMPORTS alone, so a file in the FMT-062 order fails the pipeline.

Why: dotnet format whitespace reads the same .editorconfig as the build and checks IDE0055 (formatting). dotnet format style reports the other IDE style diagnostics, including IDE0003 (this. qualification) and IDE0049 (BCL type names), which dotnet build does not report on SDK 10.0.300 with the shipped severities. The style step is therefore how CI catches this. qualification and BCL type names. The style step reports IMPORTS for a using list that has an alias before a using static directive or that is sorted all alphabetically with a namespace before System, both allowed by FMT-062, and no option turns that report off, so the step exits with code 2 for IMPORTS alone. The script fails on any exit code other than 0 or 2, and on every report entry whose DiagnosticId is not IMPORTS; IMPORTS entries alone pass. It also fails when the report is missing or empty, and it deletes the old report first so that a stale file is never read. The final exit 0 keeps a CI host that appends exit $LASTEXITCODE from failing the job with the exit code of the style step. In Windows PowerShell 5.1, do not merge the error stream of the style command into its output (2>&1) while $ErrorActionPreference is Stop, because the IMPORTS line on the error stream then stops the step. The IDE command that sorts usings and dotnet format move using static directives before aliases, so they are not used to sort the using list; no tool checks the order. Run both steps after the build, so that compile errors are reported before formatting differences. Locally, run dotnet format whitespace before you commit and apply style fixes in the IDE.

Scope: Continuous-integration pipelines · Enforced: Manual · Sources: MS-CAOV, MS-IDE

TOOL-016

DO keep the StyleCop.Analyzers package reference commented out until a stable release supports C# 14, and keep the SA rules that contradict this guide (SA1101, SA1122, SA1200, SA1208, SA1216, SA1309, SA1413, SA1600-SA1602, SA1611, SA1633, SA1649) at none.

✅ Correct — the reference stays inside an XML comment in Directory.Build.props

<!--
<ItemGroup>
  <PackageReference Include="StyleCop.Analyzers" Version="1.3.82-beta" PrivateAssets="all" />
  <AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" Link="stylecop.json" />
</ItemGroup>
-->

✅ Correct — the conflicting SA rules are preset to none (two of the thirteen lines)

# TOOL-016
dotnet_diagnostic.SA1101.severity = none
# TOOL-016
dotnet_diagnostic.SA1309.severity = none

❌ Incorrect — an active reference to the stable release

<ItemGroup>
  <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" /> <!-- Wrong: the stable release reports false positives on C# 12 to 14 syntax. -->
</ItemGroup>

❌ Incorrect — conflicting SA rules switched on

# Wrong: SA1309 forbids the underscore prefix that NAM-200 requires for private fields.
dotnet_diagnostic.SA1309.severity = warning
# Wrong: SA1101 requires the this. qualifier that TYPE-014 forbids.
dotnet_diagnostic.SA1101.severity = warning

Why: The last stable StyleCop.Analyzers release, 1.1.118 (2019-04-29), reports false positives on valid C# 12 to 14 code: SA1010 on collection expressions, SA1313 on positional record parameters and SA1101 on extension-block receivers. The prerelease 1.3.82-beta (published 2026-10-15) does not report these on the same sample, and the shipped reference uses it. Before you move to a newer prerelease such as 1.3.98-beta, run the same sample through your own build. Because it is a prerelease, the package reference ships commented out. The SA rules at none contradict these rules: SA1101 (TYPE-014); SA1309, which forbids the leading underscore (NAM-200, NAM-210); SA1122 (VAR-032); SA1200 (FMT-061); SA1208 and SA1216 (FMT-062), which require System first and using static before aliases; SA1413 (FMT-052); SA1600 to SA1602 (DOC-023); SA1611 would demand <param> tags for primary-constructor parameters; SA1649 expects file names such as Result{T}.cs, while NAM-033 uses Result.cs. SA1633 requires a file header, and the shipped files set none. SA1310 stays on: it leaves the _, m_, s_ and t_ prefixes to SA1308 and SA1309 and reports underscores in other field names (order_count, orderCount_s, private MAX_ITEMS), so it agrees with NAM-016 (NativeMethods classes are exempt). SA1308 (no m_, s_ or t_ prefix) and SA1311 (static readonly fields start upper-case) agree with NAM-210 to NAM-212 and stay on; SA1309 (no leading underscore) contradicts the _ prefix and stays at none. stylecop.json carries the matching settings (indentation 4 spaces, System usings first and outside the namespace, no blank lines between using groups, newline at end of file) and is read only when the package is enabled. Its System-first setting is read only by SA1208, which is at none. For ReSharper and Rider, StyleCop settings override EditorConfig when "Read code style from StyleCop files" is on (TOOL-022).

Exceptions: A team that enables the package accepts the remaining findings or sets them to none in a nested .editorconfig. SA1402, SA1505 and SA1508 stay on because they agree with FMT-064 and FMT-044: they fire on code that breaks those rules (several types in one file, a blank line next to a brace), including new-project template code. SA1201 also stays on in the shipped file, but it conflicts with TYPE-010 on nested types: its documented order puts nested delegates, enums and interfaces before properties and nested structs and classes last, while TYPE-010 puts all nested types last, so it can report code that follows this guide. Set it to none in a nested .editorconfig if you enable the package. Recheck the ReSharper hints against this guide afterwards.

Scope: StyleCop.Analyzers package reference and SA severities · Enforced: None while the package reference is commented out · Config: dotnet_diagnostic.SA*.severity · Sources: SA, SA-REL, SA-NUGET, RT-VER, RS-STYLECOP

Suppression and review

These rules cover how to silence a finding, what reviewers check by hand, and how analyzer packages, tags and IDE settings stay consistent.

TOOL-017

DO suppress a diagnostic only on the narrowest scope, with #pragma warning disable <ID> and a matching restore, or with [SuppressMessage] that sets Justification, and never by lowering a severity for the whole repository to hide one finding.

✅ Correct — an attribute with a justification

[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5394", Justification = "Demo data only.")]
public static int PickDemoIndex(int count) => Random.Shared.Next(count);

✅ Correct — a #pragma pair around the one statement

public static int PickSampleIndex(int count)
{
#pragma warning disable CA5394 // Demo data only; not security-relevant.
    int index = Random.Shared.Next(count);
#pragma warning restore CA5394

    return index;
}

❌ Incorrect — no matching restore, no Justification

public static int PickBadIndex(int count)
{
#pragma warning disable CA5394 // no restore: the suppression leaks to the rest of the file
    return Random.Shared.Next(count);
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5394")] // no Justification: the reason is lost
public static int PickLooseIndex(int count) => Random.Shared.Next(count);

Why: A suppression on one statement or member hides one finding; a severity lowered for the repository hides every future finding of that ID. The Justification and the comment after disable record why the finding is acceptable, which a reviewer can then challenge. Both forms work in dotnet build for analyzer diagnostics such as IDE1006 and CA5394. IDE0079 (unnecessary suppression) runs only in the editor, so CI does not flag a stale suppression; reviewers check it (TOOL-018).

Exceptions: The shipped test-file section sets CA1707, CA2007 and the Async suffix rule to none for test projects, because test method names use underscores and never end in Async, and tests need no ConfigureAwait. That is a severity setting, not a suppression. No shipped rule checks that test method names end in _Test (TEST-011). Do not add suppressions to generated code. The .NET analyzers skip files that look generated (names such as .designer.cs and .generated.cs, or an auto-generated header comment), and Microsoft documents an EditorConfig option for marking further files as generated (MS-CFG); the shipped file uses it only for EF Core migration files (DATA-006). A [ThreadStatic] field needs no suppression: it is named _ followed by camelCase, like any other private static field (NAM-212).

Scope: Suppressions of any diagnostic in source code · Enforced: Manual · Sources: MS-IDE, MS-CFG, SA

TOOL-018

DO check every changed file against the rules in the "Manual review only" table, because no build diagnostic enforces them.

✅ Correct — a review checklist that names the manual rules and the review-only checks

Review checklist (excerpt)
[x] NAM-013 abbreviations: checked in every changed file
[x] TYPE-010 member order: checked in every changed file
[x] FMT-040 line length: no line longer than 120 characters
[x] FMT-062 using order: System first or alphabetical, aliases, then using static
[x] ASYNC-012 token default: every async method's token parameter has = default

❌ Incorrect — a green build is taken as approval

Review: build is green, approved   # Wrong: the manual rules were not checked, and the build cannot check them

Why: A manual rule has no tool check at any severity, so a green build says nothing about it. The table in Manual review only lists each manual rule, its page and the reason no diagnostic exists. Use it as the review checklist; examples are NAM-013, TYPE-010 and FMT-040. IDE-only diagnostics that dotnet build never reports are checked in CI by the dotnet format style step (TOOL-015).

Scope: Code reviews of every pull request · Enforced: Manual · Sources: MS-EOB, MS-IDE

TOOL-019

DO keep the security analyzers listed in the # security-baseline block at warning (suggestion for the noisy ones), each on its own dotnet_diagnostic line, and raise individual IDs to error in a project once it has no findings for them.

✅ Correct — one line per ID in the shipped block, raised to error in a clean project

# security-baseline
dotnet_diagnostic.CA5359.severity = warning
dotnet_diagnostic.CA3001.severity = suggestion
# src/Contoso.Orders/.editorconfig
[*.cs]
dotnet_diagnostic.CA5359.severity = error

❌ Incorrect — a category line instead of per-ID lines

# Wrong: a category severity does not enable rules that are off by default, so CA5394 and CA3001 stay silent.
dotnet_analyzer_diagnostic.category-Security.severity = warning

Why: The line dotnet_analyzer_diagnostic.category-Security.severity = warning reports CA5350 and CA5351 but not CA5394, and on a project with tainted data flow it reports nothing from CA3001, CA3003 or CA2100; the global line behaves the same. Only a dotnet_diagnostic.<ID>.severity line turns those rules on, so every ID has its own line. The property AnalysisLevelSecurity is the alternative: latest-all enables every security rule at warning, including rules that no rule in this guide owns. The shipped Directory.Build.props leaves it unset and keeps the latest-all line commented out. The block's IDs that no rule owns ship at warning, and the taint rules CA3001 to CA3012 plus CA1062, CA1727 and CA1848 at suggestion; CA1307 is not in the block, because LANG-041 owns it at warning. Raising an ID to error in a nested .editorconfig (TOOL-010) keeps a clean project clean even if a run overrides TreatWarningsAsErrors, because the per-ID severity is not the property that the override changes. The IDs that have an owning rule are listed in the Enforced column of the rule index on page 13 and on page 90. Shipping security IDs at error fails builds of code that has not been triaged.

Exceptions: CA1031, CA1063 and CA1816 keep suggestion although their owning rules are DO-level (ERR-012, ERR-021). At warning they would flood new projects: process boundaries legitimately catch Exception, and the dispose pattern is a convention that a tool cannot judge case by case.

Scope: Security analyzers configured in the security-baseline block · Enforced: Manual · Config: dotnet_diagnostic.<ID>.severity · Sources: MS-CA, MS-CFG, MS-CAOV

TOOL-020

DO reference analyzer packages with PrivateAssets="all" and pin their versions in Directory.Packages.props with central package management.

✅ Correct — the version in one place, the reference without a version

<!-- Directory.Packages.props -->
<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="StyleCop.Analyzers" Version="1.3.82-beta" />
  </ItemGroup>
</Project>
<!-- Contoso.Orders.csproj -->
<ItemGroup>
  <PackageReference Include="StyleCop.Analyzers" PrivateAssets="all" />
</ItemGroup>

❌ Incorrect — a version in the project, or no PrivateAssets

<!-- Contoso.Orders.csproj -->
<PackageReference Include="StyleCop.Analyzers" Version="1.3.82-beta" PrivateAssets="all" /> <!-- Wrong: the version lives in the project; versions drift, and with central management NuGet reports NU1008. -->
<PackageReference Include="StyleCop.Analyzers" /> <!-- Wrong: no PrivateAssets, so the analyzer flows to consumers of your NuGet package. -->

Why: PrivateAssets="all" keeps the analyzer out of the dependencies of a package you publish. Central package management keeps one version per package for the whole repository. Pin an exact version and review it on every update; do not use a floating range for an analyzer that runs inside your build. The analyzers built into the SDK are not packages, and AnalysisLevel = latest-recommended follows the SDK; they stay fixed because global.json pins the SDK (TOOL-014), so the same rule holds for them: their version changes when someone raises the pin or a newer 10.0.3xx SDK is installed, which is why build agents and developer machines use the same SDK patch. The commented-out StyleCop block in the shipped Directory.Build.props is written for the case without central management (version on the reference); when the repository uses Directory.Packages.props, move the version there and remove the Version attribute, otherwise NuGet reports NU1008. Per-project package versions without central management let analyzer versions drift between projects.

Scope: Analyzer package references · Enforced: Manual · Sources: SA-NUGET, MS-CAOV

TOOL-021

DO put a # <RULE-ID>[, <RULE-ID>] comment line above each property, keep untagged lines only in the header, # shared and # security-baseline blocks, and never write a comment after a value on the same line.

✅ Correct — the tag on its own line above the property

# FMT-060
csharp_style_namespace_declarations = file_scoped

❌ Incorrect — the tag after the value

# Wrong: the tag is an inline comment, which some EditorConfig parsers read as part of the value.
csharp_style_namespace_declarations = file_scoped # FMT-060

Why: The tag links each property to the rule that owns it, so a maintainer who retires or changes a rule finds every line to edit (Maintaining this guide). Roslyn strips a trailing comment (true # VAR-010 gives the same result as the tag on its own line), but other EditorConfig parsers, among them ReSharper, Rider and the editorconfig-core libraries, do not promise to. No build tool checks the convention; the maintainer checks it by reading the diff.

Scope: Every property line of the shipped .editorconfig · Enforced: Manual · Sources: MS-CFGFILES, RS-EDITORCONFIG

TOOL-022

DO turn on reading settings from EditorConfig for both code style and inspections, and leave "Read code style from StyleCop files" off.

✅ Correct — both EditorConfig switches on, StyleCop reading off

Rider
  Settings | Editor | Code Style          -> Enable EditorConfig support: on
  Settings | Editor | Inspection Settings -> Read settings from editorconfig, project settings and rule sets: on
ReSharper
  Options | Code Inspection | Settings    -> Read settings from editorconfig and project settings: on
  Options | Code Editing | General Formatter Style -> Read code style from StyleCop files: off

❌ Incorrect — StyleCop reading on

ReSharper
  Options | Code Editing | General Formatter Style -> Read code style from StyleCop files: on   # Wrong: StyleCop settings then override the EditorConfig values of this guide

Why: JetBrains documents two EditorConfig switches: one for formatting and syntax style (Rider: Enable EditorConfig support; ReSharper: a checkbox on the General formatter page, whose path the documentation prints as "Code Editing | C++ | Formatting Style | General") and one for inspections and naming. EditorConfig properties override the preferences in all ReSharper and Rider settings layers, and EditorConfig naming rules override the Naming Style page. With StyleCop reading on, StyleCop settings override EditorConfig, and ReSharper also applies StyleCop.Analyzers defaults when that package is installed. While the package is commented out the risk is small, but the checkbox is a per-machine setting, so keep it off (TOOL-016). Visual Studio needs no setting: it reads .editorconfig when the solution opens (Adopting this style). Per-user DotSettings differ between machines, and EditorConfig overrides them.

Exceptions: Settings with no EditorConfig key stay outside this file. Member order (File Layout) is not stored in .editorconfig according to the documentation, so TYPE-010 is checked in review.

Scope: ReSharper and Rider settings on developer machines · Enforced: Manual · Sources: RS-EDITORCONFIG, RD-EDITORCONFIG, RS-STYLECOP

Manual review only

TOOL-018 requires reviewers to check this table. Each row is a rule that no build diagnostic enforces at any severity, with its page and the reason. The reasons are: no analyzer exists for the topic, the diagnostic runs only in the editor and is not caught by the dotnet format steps either, or the tool cannot express the rule. Reviewers check every row against every changed file.

ID Rule Page Why manual
ASYNC-015 DO await the inner task when the method has a using declaration or a try block around the call, and return the task without async and await only from a method that just forwards the call, optionally after synchronous argument validation. 11 no .NET SDK analyzer has a diagnostic for this convention.
ASYNC-021 DO update a mutable static field only inside a lock on a Lock field or through Interlocked, and hold shared static collections in a concurrent or immutable collection type. 11 no .NET SDK analyzer has a diagnostic for this convention. (CA2211 covers visibility, not thread safety.)
DATA-001 DO name a DbContext subclass <Domain>DbContext (OrderingDbContext), never Context, DataContext, AppDbContext or MyDbContext. 14 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
DATA-003 DO name each DbSet<T> property with the plural of its entity and declare it as an expression-bodied call to Set<T>() (public DbSet<Order> Orders => Set<Order>();). 14 no diagnostic in the .NET SDK or the EF Core analyzers checks DbSet declaration style or plural names.
DATA-006 DO give a migration a descriptive imperative PascalCase name (AddShipmentTrackingNumber), never Migration1, Update or Fix, and never hand-format or rename generated migration files afterwards. 14 no diagnostic checks migration names; the shipped .editorconfig sets generated_code = true for files in a Migrations folder (any depth) whose names contain an underscore or end in .Designer.cs or ModelSnapshot.cs, so analyzers, security rules included, do not run on them, including hand-written files with such names; the match is by name, not by authorship, and under a Migrations folder any .cs file whose name contains an underscore is treated as generated, hand-written FluentMigrator or DbUp files included; the folder name is matched with its exact case; raw SQL in a migration is reviewed by hand.
DATA-012 DO name a query method after what it returns: Get…Async when the result must exist (throws otherwise), Find…Async when it may return null, List…Async for collections, Exists…Async for bool and Count…Async for counts. 14 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
DATA-020 DO add AsNoTracking() to every EF Core query whose entities are only read and never saved. 14 no analyzer knows whether a query result is saved later.
DATA-021 DO NOT query related rows once per parent row (the N+1 pattern); load them in the same query with Include or a Select projection. 14 no analyzer detects a query inside a loop or lazy loading by itself.
DATA-022 DO NOT call ToList, ToArray, ToListAsync or AsEnumerable before a Where, OrderBy, Skip, Take or aggregate that the database can run; put those operators first and materialize last. 14 no analyzer reports LINQ operators that run in memory on rows that already left the database.
DATA-023 DO bound every query that returns a list, with Take after a unique OrderBy (Skip and Take for numbered pages) or with a keyset Where on the sort key (Id > lastId) for deep pages. 14 no analyzer knows how many rows a query can return or whether a page has a unique order.
DATA-024 CONSIDER project a read-only result into a small type with Select instead of loading whole entities. 14 no analyzer can tell which columns a caller needs.
DI-010 DO take dependencies through the constructor (a primary constructor is fine, see LANG-012), and never resolve services from IServiceProvider inside business code (the service locator pattern). 16 no .NET SDK analyzer reports a call to GetService or GetRequiredService in business code, or a dependency created with new.
DI-011 DO register each service with the lifetime its state requires: singleton for stateless or thread-safe shared state, scoped for per-request or unit-of-work state (a DbContext), transient for lightweight stateless services. 16 no .NET SDK analyzer knows the state of a service, so no diagnostic checks the lifetime chosen for it.
DI-012 DO NOT inject a scoped service, or a transient IDisposable, into a singleton (a captive dependency); create a scope with IServiceScopeFactory for each unit of work and resolve the service inside it. 16 no .NET SDK analyzer checks registrations against constructor parameters; the container reports a scoped service in a singleton at run time when ValidateScopes is on (DI-013).
DI-013 CONSIDER turning on ValidateScopes and ValidateOnBuild in every environment, so that a captive dependency or a missing registration fails when the application starts. 16 the option is set in code and no analyzer reports it missing; the container itself performs the checks at run time.
DI-020 DO keep an endpoint thin: bind and validate the input, call one application service, and map the outcome to an HTTP result with TypedResults (or Results) or ProblemDetails, with no data access and no business logic in the endpoint body. 16 no .NET SDK analyzer checks what an endpoint body contains.
DOC-010 DO write comments with // followed by one space, on their own line above the code they explain, as sentences that start with a capital letter and end with a period, and do not use /* */ comments. 09 no .NET SDK analyzer has a diagnostic for this convention.
DOC-011 DO write a comment only to explain why the code does something (a business rule, a workaround, a non-obvious constraint), never to restate what the code does. 09 no .NET SDK analyzer has a diagnostic for this convention.
DOC-012 DO NOT leave commented-out code in a file; delete it and rely on version control to recover it. 09 no .NET SDK analyzer has a diagnostic for this convention.
DOC-013 DO NOT commit a TODO, HACK, FIXME or similar marker comment; open an issue for the remaining work and reference it in the pull request instead. 09 no .NET SDK analyzer has a diagnostic for this convention.
DOC-014 DO NOT add a banner comment with copyright, author, creation date or change history at the top of a source file; version control and the repository licence file carry that information. 09 IDE0073 checks headers only when file_header_template is set, and this configuration leaves it unset.
DOC-020 DO document every public and protected type and member of a library with <summary>, and add <param> for each parameter, <returns> for non-void results and <exception> for each exception the member throws on purpose. 09 completeness is checked only by CS1591, which the shared configuration ships at none (DOC-023); library projects opt in.
DOC-021 DO document an override or interface implementation with /// <inheritdoc/> instead of copying the base documentation, and add text only for behaviour that differs. 09 no .NET SDK analyzer has a diagnostic for this convention.
ERR-016 DO report an expected failure, such as invalid user input or a missing optional record, through the Try pattern or a result type, and throw exceptions only for failures the caller cannot reasonably anticipate. 10 no .NET SDK analyzer has a diagnostic for this convention.
ERR-017 DO rethrow an exception that was captured outside its catch block with ExceptionDispatchInfo.Capture(ex).Throw() so the original stack trace survives. 10 no .NET SDK analyzer has a diagnostic for this convention.
ERR-018 DO NOT catch NullReferenceException, IndexOutOfRangeException, AccessViolationException or other exceptions that signal a defect; fix the defect instead. 10 no diagnostic flags catching NullReferenceException or IndexOutOfRangeException; CA2153 needs the obsolete HandleProcessCorruptedStateExceptions attribute (SYSLIB0032), so it does not cover these catches and stays in the security baseline instead.
ERR-022 DO obtain HttpClient instances from IHttpClientFactory or reuse one long-lived instance, and never create and dispose an HttpClient per request. 10 no .NET SDK analyzer has a diagnostic for this convention.
ERR-030 DO give every error a stable machine-readable code, declare each code once as a const string in one static class per area, reuse that constant at every call site, and declare the error's message next to its code. 10 no .NET SDK analyzer has a diagnostic for this convention.
FMT-062 DO order using directives either with System namespaces first and the rest alphabetically, or all alphabetically, with no blank lines between groups, followed by using aliases and then all using static directives at the end, each group in alphabetical order. 01 no tool checks this order; the IDE sort and dotnet format produce a different order, and the CI style step ignores IMPORTS.
FMT-064 DO declare exactly one top-level type in each file; nested types and file-local helper types stay with the type that uses them. 01 no IDE rule enforces one type per file; SA1402 ships only with StyleCop, commented out.
FMT-065 DO name each source file exactly after the single top-level type it contains, with the same casing (OrderService.cs for OrderService); generic types and partial types follow NAM-033 and NAM-034. 01 IDE1006 has no solution, project or file kind; no diagnostic in the .NET SDK checks file or project names.
FMT-066 DO NOT use #region and #endregion in hand-written code; split a type that needs regions into smaller types or partial files instead. 01 Roslyn has no #region rule; SA1124 exists only in StyleCop, which ships commented out.
LANG-040 DO build a string from a few parts with interpolation, from a sequence with string.Join or string.Concat, and in a loop with a StringBuilder, never with += on a string inside a loop. 07 no .NET SDK analyzer has a diagnostic for this convention. (CA1834 and CA1845 cover single calls, not the choice of technique.)
LANG-050 DO write LINQ queries in method syntax (orders.Where(...).Select(...)) and use query syntax only for joins, let clauses or several from clauses. 07 no .NET SDK analyzer has a diagnostic for this convention.
LANG-060 DO declare new extension members in C# 14 extension(...) blocks inside the extension class that NAM-127 names, and add an extension only for a type you cannot change. 07 no .NET SDK analyzer has a diagnostic for this convention. (No IDE rule covers extension members.)
LANG-061 AVOID goto and statement labels; write a loop, an early return or a local function instead. 07 the only Roslyn labeled-jump rule (IDE0410) needs C# 15; no diagnostic covers goto or labels.
LANG-063 DO write a null-conditional assignment (customer?.Email = email;) instead of an if (customer is not null) block around a single assignment. 07 no diagnostic in the .NET SDK suggests C# 14 null-conditional assignment.
LANG-064 DO use a checked expression or block wherever an integer overflow must throw instead of wrapping (sizes, money in minor units, counters used for allocation). 07 no diagnostic in the .NET SDK reports arithmetic that can overflow; CheckForOverflowUnderflow is a project-wide compiler switch, not a diagnostic.
NAM-010 DO write a two-letter acronym in PascalCase identifiers fully in upper case (IOStream, UIState) and an acronym of three or more letters with only its first letter capitalized (XmlReader, HttpClientFactory, JsonOptions). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. ReSharper abbreviations list has no EditorConfig key.
NAM-011 DO write an acronym that starts a camelCase identifier entirely in lower case, whatever its length (ioStream, xmlReader, httpClient, _uiState). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-012 DO write Id and Ok as ordinary words (CustomerId, IsOk), closed compounds as one word (Email, Endpoint, Metadata, Callback) and the two-word terms UserName, FileName and LogOn with a capital on each word, never ID, OK, EMail, Username or Filename. 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-013 DO NOT shorten a word in an identifier except to the approved forms Id, Ok, Db, IO, UI, Xml, Json, Http, Url, Uri, the loop counters i, j, k, the catch variable ex, the event-data parameter e (NAM-145) and a one-letter parameter of a single-line lambda (NAM-232). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. ReSharper abbreviations list has no EditorConfig key.
NAM-014 DO write identifiers as English words spelled with the ASCII letters A-Z, a-z and digits only. 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. SA1317 exists only in the commented-out StyleCop 1.3.x.
NAM-015 DO NOT declare an identifier that needs the @ verbatim prefix, such as @class or @event, except in generated interop code that must mirror an external name. 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. CA1716 exists but also flags Visual Basic keywords such as Next or Step, so the shipped .editorconfig sets it to none.
NAM-020 DO name a Boolean variable, field or parameter as an affirmative statement that starts with is, has, can or should (isPaid, hasLines, canShip, _isClosed). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-021 DO name a variable, field or parameter that holds a collection with a plural noun (orders, lines, _pendingOrders), not with a List, Array or Collection suffix. 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-022 DO put the unit at the end of the name of a numeric field, parameter, property or local that is not a TimeSpan (weightInKilograms, MaxPayloadBytes, distanceInKilometres). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-023 DO NOT tell two names apart with a numeric suffix (order2, customer1, ProcessOrder2); name each after its role instead (originalOrder, updatedOrder). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-025 DO keep generated code in files the analyzers recognize as generated (*.g.cs, *.Designer.cs or an // <auto-generated/> header) and never rename identifiers inside them to satisfy these naming rules. 02 no diagnostic checks how generated code is marked; the shipped .editorconfig sets generated_code only for such migration files, matched by name, with the folder name Migrations in its exact case, so hand-written files with an underscore in their names there are treated as generated too (DATA-006); everywhere else analyzers skip *.g.cs, *.Designer.cs and <auto-generated> files by convention.
NAM-026 DO end the name of a DateTime that holds a UTC instant with Utc (CreatedUtc, expiresUtc); the names of DateTimeOffset values stay unchanged (VAR-040). 02 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-030 DO name solutions, projects and assemblies <Company>.<Product>[.<Feature>] in PascalCase, with the solution named after the product (Contoso.Orders.sln, Contoso.Orders.Billing.csproj). 02 IDE1006 has no solution, project or file kind; no diagnostic in the .NET SDK checks file or project names.
NAM-033 DO name the file of a generic type after the type without its arity or type parameters (Result.cs holds Result<TValue>), and keep a generic and non-generic type of the same name in that one file. 02 IDE1006 has no solution, project or file kind; no diagnostic in the .NET SDK checks file or project names.
NAM-034 DO name the main file of a partial type <Type>.cs and every other part <Type>.<Role>.cs (Customer.cs, Customer.Validation.cs, OrderService.Logging.cs). 02 IDE1006 has no solution, project or file kind; no diagnostic in the .NET SDK checks file or project names.
NAM-035 DO keep a nested type in the file of its containing type and a file-local type in the one file that uses it, without separate files for either. 02 IDE1006 has no solution, project or file kind; no diagnostic in the .NET SDK checks file or project names.
NAM-036 DO name each unit-test project <ProjectUnderTest>.Tests and each integration-test project <ProjectUnderTest>.Integration.Tests, or place test projects under a tests/ folder, so the test-file section matches them. 02 IDE1006 has no solution, project or file kind; no diagnostic in the .NET SDK checks file or project names.
NAM-111 DO NOT add a Base suffix to an abstract or base class; name it after the abstraction it represents (PaymentProvider, not PaymentProviderBase). 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-127 DO put extension members in a static class named <ExtendedType>Extensions (OrderExtensions, StringExtensions), one class per extended type. 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. IDE1006 cannot select static classes that contain extension members.
NAM-132 DO start the name of a method that returns bool with Is, Has, Can or Try so that the call reads as a yes/no question (IsEligibleForDiscount, HasOpenOrders, CanShip); Task<bool> query methods named Exists…Async follow DATA-012. 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. IDE1006 cannot select methods by return type.
NAM-133 DO name a method that reports failure through its return value Try<Verb>, return bool, put the result in an out parameter declared last, and set that parameter to default when the method returns false. 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. IDE1006 cannot select methods by return type or out parameters.
NAM-141 DO name a Boolean property as an affirmative statement that starts with Is, Has or Can (IsShipped, HasLines, CanBeCancelled), never as a negative (IsNotShipped). 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-142 DO name a collection property with a plural noun (Lines, Tags, PendingOrders), not with a List, Array or Collection suffix, unless the type itself is a named collection. 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-143 DO keep the default indexer name Item and rename it with [IndexerName] only when another .NET language or an interop contract needs a specific name. 03 IDE1006 has no symbol kind for this identifier; no diagnostic in the .NET SDK checks it.
NAM-145 DO raise each event of an unsealed class from a protected virtual method named On<EventName> that takes the event data as one parameter named e. 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-146 DO name an event handler method On<Source><Event> (OnOrderShipped, OnPaymentCaptured) and never <Source>_<Event>. 03 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
NAM-216 CONSIDER name a local constant in camelCase (const int maxAttempts = 3;); PascalCase (MaxAttempts) is accepted. 04 IDE1006 cannot accept two styles for one kind of symbol, so the naming rule ships at none; only ReSharper InconsistentNaming in the editor reports a local constant.
NAM-234 DO name tuple elements in method signatures, properties and fields in PascalCase ((int Count, decimal Total)), and the variables you deconstruct them into in camelCase (NAM-235). 04 IDE1006 does not support tuple elements; no other diagnostic checks tuple element casing.
NAM-237 DO name LINQ range variables and LINQ lambda parameters with the singular camelCase noun of the element (from order in orders, orders.Where(order => order.IsShipped)). 04 IDE1006 has no kind for query range variables; no diagnostic checks lambda or range-variable word choice.
NAM-240 DO name anonymous-type members in PascalCase, either explicitly (new { OrderId = order.Id }) or by projecting a PascalCase property (new { order.Total }). 04 IDE1006 has no kind for anonymous-type members; no diagnostic checks their casing.
NAM-241 DO name a statement label in PascalCase (RetryPayment:) and add a label only where a goto is clearer than a loop or a method (see LANG-061). 04 IDE1006 has no label kind; no diagnostic checks label names.
SEC-012 DO compare secrets, tokens, signatures and message authentication codes with CryptographicOperations.FixedTimeEquals, never with ==, string.Equals or SequenceEqual. 13 no diagnostic in the .NET SDK detects timing-unsafe comparison of secrets.
SEC-031 DO start an external process with ProcessStartInfo.ArgumentList and UseShellExecute = false, and never pass untrusted input through a shell (cmd /c, sh -c) or a concatenated Arguments string. 13 the taint rule CA3006 tracks only HTTP request input and cannot follow library code; it is kept at suggestion in the security baseline.
SEC-040 DO combine an untrusted path segment with Path.Join, canonicalize the result with Path.GetFullPath, and accept it only if it starts with the base directory (compared with StringComparison.Ordinal, base path ending in a separator). 13 the taint rule CA3003 tracks only HTTP request input; it stays at suggestion in the security baseline.
SEC-072 DO NOT put secrets, credentials, connection strings, SQL text, full personal data or internal file paths into an exception message or error response that reaches a caller; log details internally and return a generic message with a correlation ID. 13 the taint rule CA3004 tracks only HTTP request input; it stays at suggestion in the security baseline.
SEC-074 DO NOT write passwords, tokens, API keys, encryption keys, full card numbers or raw request and response bodies to a log; log identifiers and counts instead. 13 no diagnostic in the .NET SDK detects sensitive data in log arguments.
TEST-010 DO name each test class after the class it tests followed by Tests (OrderServiceTests for OrderService). 12 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits. IDE1006 cannot select test classes.
TEST-012 DO name a hand-written test double Fake<Name> when it is a working in-memory implementation, Stub<Name> when it returns canned answers and Spy<Name> when it records calls, and name a test-data builder <Type>Builder. 12 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
TEST-013 DO name each [MemberData] or [ClassData] source after the scenario its rows supply (LinesWithQuantityAndPrice), never TestData, Data or Cases1. 12 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
TEST-014 DO name the object under test after its type in camelCase (orderService), the expected value expected and the observed value actual, never sut, result1 or x. 12 IDE1006 naming styles can only check capitalization, prefix, suffix and word separator, so word choice is inexpressible; no other .NET SDK diagnostic checks it. ReSharper InconsistentNaming has the same limits.
TEST-020 DO put each test class in <Project>.Tests at the same relative folder and namespace as the class it tests (Contoso.Orders/Shipping/CarrierClient.cs is tested in Contoso.Orders.Tests/Shipping/CarrierClientTests.cs, namespace Contoso.Orders.Tests.Shipping). 12 no .NET SDK analyzer has a diagnostic for this convention.
TEST-021 DO split every test body into Arrange, Act and Assert sections, each introduced by a // Arrange, // Act or // Assert comment and separated by one blank line. 12 no .NET SDK analyzer has a diagnostic for this convention.
TEST-022 DO verify one behaviour per test: write exactly one Act statement and assert only on the outcome of that statement. 12 no .NET SDK analyzer has a diagnostic for this convention.
TEST-023 DO NOT write loops, if or switch statements or computed expected values (string building, arithmetic over the inputs) in a test body; supply each case as a [Theory] row through [InlineData] or [MemberData] instead. 12 no .NET SDK analyzer has a diagnostic for this convention.
TOOL-010 DO copy config/.editorconfig to the repository root with root = true and put project-specific overrides in .editorconfig files nested below it, never in edited copies of the root file. 15 precedence (root = true, deeper file wins) is a file-placement rule that no diagnostic can check.
TOOL-011 DO write code-style option values without a :severity suffix and set each diagnostic's severity once, with dotnet_diagnostic.<ID>.severity. 15 dotnet build honours both forms, so no diagnostic flags the suffix; the single form avoids two severities drifting.
TOOL-012 DO set dotnet_diagnostic.IDE1006.severity = warning whenever the file defines naming rules, because a naming rule's own severity does not make it fire in dotnet build. 15 a naming rule's own severity does not fire in dotnet build, and nothing reports the missing IDE1006 line.
TOOL-013 DO add a resharper_* key with the same value next to every Roslyn key that the JetBrains documentation does not list as read, such as csharp_style_namespace_declarations, csharp_style_implicit_object_creation_when_type_is_apparent, csharp_prefer_simple_default_expression and the expression-body options for operators, indexers, local functions and lambdas. 15 ReSharper does not document reading these Roslyn keys; nothing checks the twins agree.
TOOL-014 DO set EnforceCodeStyleInBuild, AnalysisLevel = latest-recommended, LangVersion = latest, Nullable = enable, ImplicitUsings = enable and GenerateDocumentationFile = true in Directory.Build.props, set TreatWarningsAsErrors to true on every build with only NU1900 and NU1801 kept as warnings, and pin the SDK in a global.json next to it. 15 these are MSBuild properties and an SDK pin; without them no IDE rule fires in the build at all.
TOOL-015 DO run dotnet format whitespace --verify-no-changes and dotnet format style --verify-no-changes --report <dir> on every pull request, and fail the pipeline when either reports a change other than the IMPORTS using order. 15 dotnet format whitespace applies the IDE0055 analyzer and dotnet format style applies the other IDE style analyzers; whether CI runs them is a pipeline setting.
TOOL-017 DO suppress a diagnostic only on the narrowest scope, with #pragma warning disable <ID> and a matching restore, or with [SuppressMessage] that sets Justification, and never by lowering a severity for the whole repository to hide one finding. 15 IDE0079 (unnecessary suppression) runs only in the IDE; nothing in the build checks justifications.
TOOL-018 DO check every changed file against the rules in the "Manual review only" table, because no build diagnostic enforces them. 15 these rules are manual because no build diagnostic exists.
TOOL-019 DO keep the security analyzers listed in the # security-baseline block at warning (suggestion for the noisy ones), each on its own dotnet_diagnostic line, and raise individual IDs to error in a project once it has no findings for them. 15 category and global severities do not enable rules that are off by default, so each ID needs its own line; the raise to error is made per project.
TOOL-020 DO reference analyzer packages with PrivateAssets="all" and pin their versions in Directory.Packages.props with central package management. 15 package reference form is an MSBuild concern that no analyzer checks.
TOOL-021 DO put a # <RULE-ID>[, <RULE-ID>] comment line above each property, keep untagged lines only in the header, # shared and # security-baseline blocks, and never write a comment after a value on the same line. 15 Roslyn tolerates inline comments, but other EditorConfig parsers do not promise to; no tool checks the tag convention.
TOOL-022 DO turn on reading settings from EditorConfig for both code style and inspections, and leave "Read code style from StyleCop files" off. 15 both are IDE option checkboxes with no EditorConfig key.
TYPE-010 DO order the members of a type as fields, constructors, events, properties, indexers, operators, methods and nested types; within each group public before internal, protected and private, and static before instance. 08 no Roslyn rule checks member order; ReSharper File Layout lives only in DotSettings and is never reported; SA1201-SA1204 ship with StyleCop, commented out.
TYPE-020 DO choose a record for immutable data compared by value, a class for an object with identity or behaviour, and a struct only for a small (16 bytes or less), immutable value that is rarely boxed. 08 no .NET SDK analyzer has a diagnostic for this convention. (The Framework Design Guidelines give criteria only.)
TYPE-021 AVOID more than three parameters, not counting a trailing CancellationToken; group related values into a record parameter object instead. 08 no .NET SDK analyzer has a diagnostic for this convention.
TYPE-023 DO use optional parameters with constant defaults instead of overloads that only supply default values, except in the public API of a shipped library, where you add overloads. 08 no .NET SDK analyzer has a diagnostic for this convention.
TYPE-032 DO declare exactly one defining part and one implementing part for each partial member, keeping the implementing part in the generated or role-specific file of the type. 08 the compiler already rejects mismatched parts; no diagnostic checks where the parts live.
VAR-016 DO declare one variable per declaration statement and declare each local in the narrowest scope, directly before its first use. 05 no .NET SDK analyzer has a diagnostic for this convention. (No IDE rule flags multiple declarators; SA1132 is StyleCop-only.)
VAR-021 DO use int for integer values unless the value range, a native interop signature or a file or wire format needs long, short, byte or an unsigned type, and keep unsigned types out of public API signatures. 05 no .NET SDK analyzer has a diagnostic for this convention. (CA1028 covers enum storage only.)
VAR-023 DO separate digit groups of a numeric literal with five or more digits with _ (1_000_000, 0xFF_FF), and write bit masks and flag values with 0b or 0x prefixes. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-024 DO use decimal for monetary amounts and double for measured or scientific quantities, and compare double or float values against a tolerance instead of with == or !=. 05 no .NET SDK analyzer has a diagnostic for this convention. (CA2242 covers NaN comparisons only.)
VAR-027 DO give every literal with a business meaning a named constant or configuration value (const int MaxLinesPerOrder = 50;), and keep inline only 0, 1, -1, "" and literals whose meaning the line states. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-031 AVOID verbatim strings (@"...") for new file paths, regular expressions and other backslash-heavy text; write them as raw string literals. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-032 DO write an empty string as "", not as string.Empty, and test for missing text with string.IsNullOrEmpty (LANG-042). 05 no Roslyn diagnostic covers empty-string style; SA1122 (string.Empty) is StyleCop-only and is turned off; ReSharper already prefers "" by default.
VAR-034 DO write an interpolated string that contains backslashes, quotes or line breaks as an interpolated raw string literal ($"""...""" or $$"""..."""), never as a verbatim interpolated string ($@"..." or @$"..."). 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-040 DO use DateTimeOffset for a point in time, such as when an order was placed or shipped. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-041 DO read the current time from an injected TimeProvider (timeProvider.GetUtcNow()) or, where no provider is available, from DateTimeOffset.UtcNow, and never use DateTime.Now or DateTimeOffset.Now for values that are stored or compared. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-042 DO use DateOnly for a calendar date such as a delivery date or birthday and TimeOnly for a time of day such as an opening time. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-043 DO represent a duration as a TimeSpan (var paymentTimeout = TimeSpan.FromSeconds(30);) instead of an int or double number of milliseconds, seconds or minutes. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-044 DO take a TimeProvider as a dependency in every class whose behaviour depends on the current time, and use FakeTimeProvider or a fake of your own in tests. 05 no .NET SDK analyzer has a diagnostic for this convention.
VAR-052 DO write a nullable value type with the ? suffix (int?, DateOnly?), never as Nullable<T>. 05 no .NET SDK analyzer has a diagnostic for this convention. (SA1125 is StyleCop-only.)
VAR-527 DO reference a static member through the type that declares it (OrderService.MaxLinesPerOrder), never through a derived type or an instance. 06 no .NET SDK analyzer has a diagnostic for this convention. (ReSharper has the inspection AccessToStaticMemberViaDerivedType.)
VAR-528 DO expose static state through a get-only static auto-property (public static TimeSpan PaymentTimeout { get; } = TimeSpan.FromSeconds(30);) or a static readonly field for an immutable value, keep mutable static state in a private static field changed only by methods, and never give a static property a public setter. 06 no diagnostic in the .NET SDK checks how a static property is declared; CA2211 (VAR-513) covers only visible non-constant fields, and CA1044/CA2227 check write-only and collection properties, not static setters.
VAR-533 DO populate a dictionary with an index initializer (["SKU-1"] = 9.99m) and pass a StringComparer (usually StringComparer.Ordinal or OrdinalIgnoreCase) whenever the key is a string. 06 no .NET SDK analyzer has a diagnostic for this convention. (C# 14 has no dictionary collection expressions.)
VAR-542 DO declare a reference record with the record keyword (not record class), use positional syntax only for small immutable data, and use a nominal record with required or init properties when it has more than about four members. 06 no .NET SDK analyzer has a diagnostic for this convention.
VAR-544 DO use an anonymous type only for a projection that stays inside one method, and use a named record when the data is returned, stored in a field or passed to another method. 06 no .NET SDK analyzer has a diagnostic for this convention.
VAR-545 DO NOT declare a variable, parameter or return type as dynamic except for COM or dynamic-language interop, or as object where a generic type parameter or a specific type expresses the same thing. 06 no .NET SDK analyzer has a diagnostic for this convention.
VAR-548 DO add to each type parameter exactly the constraints the generic code needs (where T : notnull, class, struct, an interface or new()), and no constraint the code does not use. 06 no .NET SDK analyzer has a diagnostic for this convention.
VAR-554 DO use ref locals, ref returns and scoped only on a measured hot path to avoid copying large structs, and prefer ref readonly when the caller must not write through the reference. 06 no .NET SDK analyzer has a diagnostic for this convention.
VAR-556 DO NOT declare a local, parameter or lambda parameter with the name of a field, property or outer local that is in scope. 06 no .NET SDK analyzer has a diagnostic for this convention. (Shadowing an outer local is already error CS0136; shadowing a member has no diagnostic.)
VAR-557 DO NOT capture the counter of a for loop in a lambda or local function; copy it to a local declared inside the loop body and capture that local. 06 no .NET SDK analyzer has a diagnostic for this convention.

Warnings on new projects

With the shipped files on SDK 10.0.300, a project from dotnet new console builds with 0 warnings and 0 errors, and so does one from dotnet new classlib when the project name is in PascalCase (Contoso.Orders). The classlib template derives the namespace from the project name, so a lower-case project name (orders) produces a lower-case namespace and one error, IDE1006. Name the project in PascalCase, or rename the namespace, before the first build. The build result does not depend on where it runs: there is no CI-only gate, and a local build and a CI build report the same findings when both use the same SDK patch (offline, the NuGet audit reports NU1900 instead of advisories).

The other templates (xunit, webapi, worker, mvc) predate this style and were not measured. Expect findings from the code they generate, and because every warning fails the build, fix the template code once when you create the project instead of lowering a severity. Suppress a finding that is a deliberate non-security use only on the narrowest scope and with a justification (TOOL-017). A template package with a known advisory fails the build with NU1901 to NU1904 until you update or accept it (TOOL-014).

Sources

Keys resolve on 92-Sources.md: MS-CFGFILES, MS-CFG, MS-CAOV, MS-CA, MS-IDE, MS-IDE-LANG, MS-IDE-NAMING, MS-MSBUILD, MS-CONV, MS-EOB, RS-EDITORCONFIG, RD-EDITORCONFIG, RS-SYNTAX, RD-NAMING, RS-STYLECOP, SA, SA-REL, SA-NUGET, RT-VER, MS-GLOBALJSON, MS-NUGET-AUDIT, MS-NUGET-PSM.

Previous: Data Access · Home · Next: Dependency Injection and Layering