Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
This guide gives one answer per C# style question and ships the configuration that checks it. Every rule has a stable ID such as NAM-210, a level, a correct and an incorrect example, the reason for the rule, and the setting that enforces it. One .editorconfig drives the Roslyn analyzers, Visual Studio, Rider and ReSharper, so most rules are checked by the build or the editor instead of by memory.
Baseline. All rules target C# 14 on .NET 10, with nullable reference types and implicit usings enabled. A rule that depends on a feature from C# 12 or later (primary constructors, collection expressions, the field keyword, extension blocks) starts with a callout such as > **C# 14:**. The callout also names the older form when the rule needs a different construct below that language version.
Scope. Style, naming, declaration and type-design conventions, plus the secure-coding, data-access and dependency-injection rules that can be stated at code-style level. Page 16 covers constructor injection, service lifetimes and the shape of an endpoint. Threat modelling, other architecture questions and the choice of test framework are out of scope.
Audience. Developers who write C#, reviewers who check it, and the people who maintain the build and CI.
Examples. Each code block is a fragment. It may show several types together, leaves out argument guards and ConfigureAwait unless the rule is about them, and omits the using directives and domain types shown elsewhere. Examples use syntax up to the C# 14 baseline. The types they use are listed under Sample domain.
Every rule traces to published sources in three families. Page 92-Sources.md lists each source with its key.
| Family | What it covers |
|---|---|
| Microsoft | .NET coding conventions, identifier naming rules, Framework Design Guidelines, the code-style (IDE) and code-quality (CA) rule documentation, and Microsoft Learn topic guidance |
| Community | The dotnet/runtime and dotnet/roslyn style files, StyleCop Analyzers, the Aviva Solutions C# Coding Guidelines, the Google C# style guide, and single-topic references (test naming, Dapper, OWASP, the IETF problem-details RFC) |
| JetBrains | Documented ReSharper and Rider defaults and resharper_* EditorConfig properties |
The families disagree on concrete points: field prefixes, this., using placement, var, member order. Where the families differ, each rule's Why paragraph gives the reason for the rule and names the other conventions.
| Question | Short answer | Rule |
|---|---|---|
var or explicit type? |
Declare locals with var. An explicit type is accepted, and it is needed where a literal would give the wrong type (9.99 is a double) or the variable must have a base type. |
VAR-010 |
| How do I name a private field? | Instance fields use _camelCase, for example _lineCount. Mutable static fields, including [ThreadStatic] ones, use the same _camelCase, for example _ordersPlaced. Static readonly fields use PascalCase with no prefix, for example Cache. Never use s_ or t_. One prefix, then camelCase: _orderCount, never _order_count or orderCount_s. |
NAM-200, NAM-210, NAM-211, NAM-212 |
Where do using directives go? |
At the top of the file, outside the namespace: System namespaces first or all alphabetical, then aliases, then using static. |
FMT-061, FMT-062 |
| How do I name async methods? | End the name with Async when the method returns Task, Task<T>, ValueTask, ValueTask<T> or IAsyncEnumerable<T>. Test methods and async void event handlers are the two exceptions. |
NAM-131 |
Do I need braces around a one-line if? |
Yes. Every control-flow body gets braces, on their own lines. | FMT-021, FMT-020 |
Do I need a blank line before return? |
Yes. One blank line before every return, throw, break, continue, goto and yield break, except as the first statement of a block or right after a label (case, default or a statement label). |
FMT-046 |
Other lookups:
- The name of an identifier kind: the naming cheat sheet. Files, projects, namespaces and tests are not cheat-sheet rows: they are named in NAM-030 to NAM-036 and TEST-010 to TEST-014.
- A rule by ID, with its level, page, enforcing analyzer and config keys: 90-Rule-Cross-Reference.md.
- Why a rule is the way it is: its Why paragraph.
- What a term means: the Glossary.
Every rule starts with one of four level keywords. The level states how strictly to follow the rule and how the shipped configuration reacts to a violation.
| Level | RFC 2119 | Meaning | Shipped severity | Effect on the build |
|---|---|---|---|---|
| DO | MUST | Always follow the rule. | warning |
Fails every build, local and CI, where a tool enforces the rule, because the build treats compiler, analyzer and NuGet warnings as errors. |
| DO NOT | MUST NOT | Never do this. | warning |
Fails every build, local and CI, where a tool enforces the rule, because the build treats compiler, analyzer and NuGet warnings as errors. |
| CONSIDER | SHOULD | Follow the rule unless you can name a specific reason not to, and give that reason in the review. | suggestion |
Never fails the build. The editor shows a hint where a check exists. |
| AVOID | SHOULD NOT | Do not do this unless you can name a specific reason, and give that reason in the review. | suggestion |
Never fails the build. The editor shows a hint where a check exists. |
Notes on how levels work:
- A DO or DO NOT rule fails a build only where a build analyzer enforces it. The
dotnet formatsteps in CI (TOOL-015) add checks the build does not report. A rule marked Review only or Manual is enforced in code review: no tool checks it, whatever its level. Page 15-Tooling-and-Enforcement.md lists all manual rules in its Manual review only table, and TOOL-018 requires reviewers to check them. - An example marked ✅ Accepted is allowed but is not the preferred form; ✅ Correct marks the preferred form.
- The shipped
Directory.Build.propsturns onTreatWarningsAsErrorsfor every build, so a violation of a DO or DO NOT rule that a build analyzer reports is a build error on your machine as well as in the pipeline (TOOL-014).TreatWarningsAsErrorsraises compiler, analyzer and NuGet warnings, not MSBuild (MSB) warnings. A single local run can pass-p:TreatWarningsAsErrors=false. For the inner loop (F5 in Visual Studio, Rider,dotnet buildanddotnet watch), a git-ignored<Project>.csproj.userfile can set the property tofalsefor that project: a plain<Project>element with onePropertyGroupthat setsTreatWarningsAsErrorstofalse. MSBuild imports it afterDirectory.Build.props, there is one per project (Visual Studio may already have created it), and the standard Visual Studio.gitignoreignores*.user. Like the-prollback, the.userfile also turnsNU1901toNU1905into warnings on that machine, so keep both out of CI, and keep the.userfile out of the repository (the-poption is a command option and is not stored). Every restore, build, test, pack and publish command on CI passes-p:TreatWarningsAsErrors=true: a global property beats a project or.uservalue, so a stray.userfile cannot switch offTreatWarningsAsErrorson CI, and an environment variable is no substitute. - A diagnostic can ship at a lower severity than its rule's level. For example,
CA2007belongs to a DO rule but ships atsuggestion, and only for DLL outputs, so test projects and application code are not flooded; library teams raise it towarning.CA1031,CA1063andCA1816also ship atsuggestion, because process boundaries legitimately catchExceptionand the dispose pattern cannot be judged case by case.CA1034ships atsuggestionbecause it reports a public C# 14extension(...)block as a nested type. The noisy security-baseline IDs, which no rule owns, ship atsuggestiontoo. The naming rule of NAM-216 (local constants) ships atnone, so the build does not report it; only ReSharperInconsistentNamingin the editor does. The shipped.editorconfiglists each severity. - This guide has no MAY level. Optional behaviour is not a rule.
These 25 rules matter most in everyday code. Each links to its rule on the owning page.
| # | ID | Rule | Page |
|---|---|---|---|
| 1 | ASYNC-010 | DO await every task through the whole call chain, and never block on a task with .Result, .Wait() or .GetAwaiter().GetResult(). |
11 |
| 2 | ASYNC-012 | DO give every async method that starts cancellable work, including an interface member, a CancellationToken cancellationToken = default as its last parameter, and pass that token to every call that accepts one. |
11 |
| 3 | ERR-011 | DO rethrow a caught exception with throw; and, when translating it to another exception type, pass the original as the inner exception. |
10 |
| 4 | ERR-014 | DO validate the arguments of public and protected members at entry with the static throw helpers (ArgumentNullException.ThrowIfNull, ArgumentException.ThrowIfNullOrWhiteSpace, ArgumentOutOfRangeException.ThrowIfNegativeOrZero, ObjectDisposedException.ThrowIf). |
10 |
| 5 | ERR-020 | DO dispose every IDisposable or IAsyncDisposable object you create or own with using or await using, and dispose disposable fields in the owning type's Dispose. |
10 |
| 6 | FMT-020 | DO put every opening brace and every closing brace on a line of its own (Allman style); a one-line block is allowed only for an accessor list such as { get; init; } and for an empty body { }. |
01 |
| 7 | FMT-021 | DO enclose the body of every if, else, for, foreach, while, do, using, lock and fixed statement in braces, even when the body is a single statement. |
01 |
| 8 | FMT-060 | DO declare the namespace of a file with a file-scoped declaration (namespace Contoso.Orders;), not with a braced namespace block. |
01 |
| 9 | FMT-061 | DO place every using directive at the top of the file, before the namespace declaration and outside any namespace. |
01 |
| 10 | LANG-041 | DO pass an explicit StringComparison to every string comparison, prefix test, search and Equals call, using Ordinal or OrdinalIgnoreCase for identifiers, keys, paths, roles and other non-linguistic values. |
07 |
| 11 | NAM-110 | DO name a class, including a static class, with a PascalCase noun or noun phrase that names what it is (OrderService, InvoiceNumberGenerator), with no C or cls prefix. |
03 |
| 12 | NAM-115 | DO prefix an interface name with I followed by a PascalCase noun or adjective (IOrderRepository, IFormattable), and give its default implementation the same name without the I (NAM-024). |
03 |
| 13 | NAM-131 | DO end the name of every method that returns an awaitable type or IAsyncEnumerable<T> with Async, except test methods and async void event handlers. |
03 |
| 14 | NAM-200 | DO name a private, internal or private protected instance field with _ followed by a camelCase noun (_lines, _timeProvider). |
04 |
| 15 | NAM-210 | DO name a private, internal or private protected static field that is not readonly, including a [ThreadStatic] field, with _ followed by camelCase, exactly like an instance field (_ordersPlaced, _retryCount), and never with an s_ prefix. |
04 |
| 16 | NAM-220 | DO name a parameter in camelCase after its meaning rather than its type (orderTotal, customerId, cancellationToken). |
04 |
| 17 | SEC-020 | DO NOT hard-code a secret, password, API key, encryption key, certificate or connection string with credentials in source code, tests or comments; read it from configuration or a secret store at run time. | 13 |
| 18 | SEC-030 | DO pass every value that goes into a SQL statement as a parameter (DbParameter, Dapper parameter object, EF Core FromSql interpolation), never by concatenating or interpolating it into the SQL text, and take table or column names only from an allow-list. |
13 |
| 19 | TYPE-012 | DO write an access modifier on every type and member, including the default private and internal, except on interface members. |
08 |
| 20 | VAR-010 | CONSIDER declare locals with var (var order = new Order(7, createdAt);, var lineCount = 0;, var order = await repository.GetAsync(orderId, cancellationToken);, foreach (var line in order.Lines)); an explicit type is accepted, and it is needed where the variable must have a base type or a literal would give the wrong type. |
05 |
| 21 | VAR-051 | DO add ? to every reference-typed field, property, parameter, return type and type argument that can hold null, and to no other reference type. |
05 |
| 22 | NAM-214 | DO name a constant field of any accessibility in PascalCase with no prefix (MaxLinesPerOrder, HttpsPort). |
04 |
| 23 | TYPE-013 | DO declare every class sealed unless it is designed and documented as a base class. |
08 |
| 24 | TYPE-014 | DO NOT qualify a member with this. unless a parameter or local of the same name hides it. |
08 |
| 25 | 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 |
You need four files from the config/ folder of this guide: config/.editorconfig, config/Directory.Build.props, config/global.json and config/stylecop.json. The .editorconfig sits in config/, not at the root of the guide, because a root-level [*] section would also apply to the guide's own Markdown.
Copy the four files to the root of your repository, next to the .sln file. This example copies them into a solution folder named Contoso.Orders:
cp config/.editorconfig ../Contoso.Orders/.editorconfig
cp config/Directory.Build.props ../Contoso.Orders/Directory.Build.props
cp config/global.json ../Contoso.Orders/global.json
cp config/stylecop.json ../Contoso.Orders/stylecop.json.editorconfigholds the naming rules, formatting options and analyzer severities. It setsroot = true, so it stops the search for parent.editorconfigfiles.Directory.Build.propssets the language version tolatestand the nullable context, turns onEnforceCodeStyleInBuild, setsAnalysisLeveltolatest-recommended, treats every warning as an error in local and CI builds, and enablesGenerateDocumentationFilefor every project below it (TOOL-014).latestandlatest-recommendedfollow the SDK in use, andAnalysisLevelalso turns the Recommended code-quality rules that have no line in the.editorconfiginto warnings, which fail the build (about 80 on SDK 10.0.300, for exampleCA1861,CA1869andCA2208). To change one, put adotnet_diagnostic.<ID>.severityline in a nested.editorconfigabove the projects (for examplesrc/.editorconfig) or in a repository.globalconfig, not under an unrelated rule tag in the copied file (TOOL-010). The compiler that runs the build resolveslatest, and Visual Studio's bundled compiler can resolve a newer C# version than the CLI on the pinned SDK, so CI is the reference.global.jsonpins the .NET SDK to10.0.300and lets it roll forward only to a newer patch of the same feature band (latestPatch). The analyzer rule set changes when you raise the pin or when a newer10.0.3xxSDK is installed; patches fix analyzers but add no new rule sets. Use the same SDK patch on build agents and developer machines, because an offline machine reportsNU1900where an online one reports advisories. A machine without a matching SDK fails every build, restore and test command below the file withA compatible .NET SDK was not found.Make CI follow the file:actions/setup-dotnetwithglobal-json-file, Azure PipelinesUseDotNet@2withuseGlobalJson, and SDK image tags in the10.0.3xxband. To fix a failure, install an SDK from the10.0.3xxband, or raisesdk.versionto the full version of an SDK you have installed (dotnet --list-sdkslists them), build, and fix the new findings in the same change. Raise the pin with each servicing cycle (TOOL-014).stylecop.jsonholds the StyleCop settings that match this guide. It has no effect until you enable StyleCop.Analyzers. The package reference ships commented out inDirectory.Build.props, because no stable release supports C# 14.- If your solution already has a
Directory.Build.props, merge the properties into it. MSBuild uses only the nearest file. - Keep project-specific overrides in nested
.editorconfigfiles, not in the copied one (TOOL-010).
Test projects must be named <Project>.Tests or live in a top-level tests folder next to the root .editorconfig; a nested tests folder is not matched. The test-file section of the .editorconfig matches those paths only (NAM-036).
Visual Studio reads .editorconfig when you open the solution. For files below it, the file overrides your personal Tools > Options > Text Editor > C# > Code Style settings. No further setup is needed. Rules that run only in the IDE, such as IDE0003 for this. qualification, never appear in dotnet build; the dotnet format style step in CI reports them.
Turn on both EditorConfig switches (RS-EDITORCONFIG, RD-EDITORCONFIG):
- Rider: Settings | Editor | Code Style, check Enable EditorConfig support. Then, under Settings | Editor | Inspection Settings, check the checkbox that reads EditorConfig settings for inspections and naming (labelled Read settings from editorconfig, project settings and rule sets).
- ReSharper: Options | Code Inspection | Settings, check Read settings from editorconfig and project settings.
- Leave Read code style from StyleCop files off. When it is on, StyleCop settings override EditorConfig (TOOL-022).
The .editorconfig carries resharper_* twins for settings ReSharper does not read from the Roslyn keys (TOOL-013).
dotnet format whitespace applies the whitespace fixes that the same analyzers report. Apply code-style fixes in the IDE. 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 (FMT-062). If you run a full dotnet format, discard the changes it makes to the using list. Run the whitespace fix before you commit:
dotnet format whitespace Contoso.Orders.slnRun the build first, then the format checks (TOOL-014, TOOL-015):
dotnet build Contoso.Orders.sln --configuration Release -p:TreatWarningsAsErrors=trueBoth dotnet format commands pass --no-restore, because the build step already restored and dotnet format takes no -p property. The first check covers whitespace. The second writes a style report. dotnet format style also reports the FMT-062 using order as IMPORTS and exits with code 2 for it, so the script ignores IMPORTS entries and fails the step on the other entries:
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 0Directory.Build.props sets TreatWarningsAsErrors for every build, and every restore, build, test, pack and publish command in the pipeline also passes -p:TreatWarningsAsErrors=true, because a global property beats a local .csproj.user file. NU1900 is an error only on CI, and only when the NU1900 option below is used. A local build reports the same findings as CI when both use the same SDK patch. --verify-no-changes makes dotnet format fail instead of rewriting files.
The build also audits the NuGet packages for known vulnerabilities, and an advisory fails it. When the audit data cannot be fetched, NU1900 stays a warning and the build passes without a check. Close that gap in one of two ways (TOOL-014). A listing step after the build reports vulnerable packages, but the command reports only and does not fail a build by itself, so a step that must fail has to check its output:
dotnet list package --vulnerable --include-transitiveOr make NU1900 an error for the CI build only, by passing -p:WarningsNotAsErrors=NU1801. A global property replaces the whole value. 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 the escaped semicolon %3B: NU1801%3B<codes your projects already list>. Never repeat NU1900 to NU1905. 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. This command replaces the build command shown above; it is not an extra step:
dotnet build Contoso.Orders.sln --configuration Release -p:TreatWarningsAsErrors=true -p:WarningsNotAsErrors=NU1801NU1900 is raised during restore, so a pipeline with a separate restore step passes both values there as well:
dotnet restore Contoso.Orders.sln -p:TreatWarningsAsErrors=true -p:WarningsNotAsErrors=NU1801The shipped Directory.Build.props also sets NuGetAudit, NuGetAuditMode and NuGetAuditLevel, so a pipeline or agent variable cannot switch the audit off or narrow it. It also sets RunAnalyzers, RunAnalyzersDuringBuild, EnableNETAnalyzers and CodeAnalysisTreatWarningsAsErrors to true, so a pipeline or agent 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. Never override NoWarn with -p: that drops the SDK's own codes.
The build catches DO and DO NOT violations that a build diagnostic reports, on your machine and in CI. The dotnet format style step in CI also catches this. qualification and BCL type names (int versus Int32), which the build does not report. CI does not check manual rules, or IDE-only diagnostics that the dotnet format style step does not report. Reviewers check those (TOOL-018).
Read 01 to 16 in order, or jump in with Find what you need. Every page links back to Home. Page order in the Azure DevOps wiki comes from the .order file.
- 01-Layout-and-Formatting.md: file encoding and indentation, braces, spacing, line length and wrapping, blank lines, initializers, file-scoped namespaces and
usingdirectives.
- 02-Naming-Cheat-Sheet-and-Principles.md: the naming cheat sheet (one row per identifier kind) and general principles: words, acronyms, meaningful names, solution, project, namespace and file names.
- 03-Naming-Types-and-Members.md: names of types, enums, delegates, methods (including the
Asyncsuffix and extension members), properties, events and indexers. - 04-Naming-Fields-Parameters-and-Locals.md: names of instance and static fields, constants, parameters, locals, lambda parameters and pattern variables.
- 05-Variables-Types-Literals-and-Nullability.md:
varversus explicit types, built-in types and literals, strings, date and time, and nullable reference types. - 06-Variables-Fields-Properties-and-Collections.md: how to declare fields, constants, properties, arrays, collections, tuples and records.
- 07-Language-Features.md: expression bodies, constructors, local functions, pattern matching, initializers,
nameof, string comparisons, LINQ, and C# 12 to 14 features. - 08-Types-and-Members.md: member order and modifiers, type and member design, events, operators, nested and partial types.
- 09-Comments-and-Documentation.md: comments and XML documentation.
- 10-Exceptions-and-Error-Handling.md: throwing and catching exceptions, argument validation, disposal and error codes.
- 11-Async-and-Concurrency.md:
asyncandawait, cancellation,ConfigureAwait, locks and shared state. - 12-Testing-Conventions.md: test class and method naming, and test layout.
- 13-Secure-Coding.md: secrets, injection, files and paths, cryptography, deserialization and XML, errors and logging.
- 14-Data-Access.md: naming and usage conventions for data-access code, including EF Core
DbSet<T>properties, and query-shape rules (tracking, N+1, filtering in the database, limits, projection).
- 15-Tooling-and-Enforcement.md: how the shipped
.editorconfig,Directory.Build.props,global.jsonandstylecop.jsonwork, the severity model, ReSharper and Rider settings, suppression, and the manual-review table.
- 16-Dependency-Injection-and-Layering.md: constructor injection, service lifetimes, captive dependencies, container validation at startup, and thin endpoints.
- 90-Rule-Cross-Reference.md: one row per rule with its level, page, enforcing Roslyn, StyleCop and ReSharper IDs, and
.editorconfigkeys. - 92-Sources.md: every source key with its title, publisher and URL.
Every example uses one fictional order-management domain, Contoso.Orders. The two files below are the types the examples rely on. Add them to the scratch project from Keeping correct examples honest, and add <Using Include="Contoso.Orders" /> to an ItemGroup in the project file, so that a pasted example can use the domain types without declaring them. They sit in one block here for brevity; in real code each type has its own file (FMT-064).
namespace Contoso.Orders;
public enum OrderStatus
{
Pending = 0,
Paid = 1,
Shipped = 2,
Cancelled = 3
}
[Flags]
public enum ShippingOptions
{
None = 0,
Express = 1,
Insured = 2,
Tracked = 4
}
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice)
{
public decimal Amount => Quantity * UnitPrice;
}
public sealed class OrderShippedEventArgs(int orderId) : EventArgs
{
public int OrderId { get; } = orderId;
}
public sealed class Customer
{
public required int Id { get; init; }
public required string Name { get; init; }
public string? Email { get; init; }
}
public abstract record Payment(decimal Amount);
public sealed record CardPayment(decimal Amount, string MaskedNumber) : Payment(Amount);
public sealed record Invoice(int Id, DateTimeOffset DueDate);
public interface IOrderRepository
{
Task<Order?> FindAsync(int orderId, CancellationToken cancellationToken = default);
Task<Order> GetAsync(int orderId, CancellationToken cancellationToken = default);
Task<IReadOnlyList<Order>> ListByCustomerAsync(int customerId, CancellationToken cancellationToken = default);
Task AddAsync(Order order, CancellationToken cancellationToken = default);
}
public sealed class OrderNotFoundException : Exception
{
public OrderNotFoundException()
{
}
public OrderNotFoundException(string message)
: base(message)
{
}
public OrderNotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
}namespace Contoso.Orders;
public sealed class Order(int customerId, DateTimeOffset createdAt)
{
private readonly List<OrderLine> _lines = [];
public event EventHandler<OrderShippedEventArgs>? Shipped;
public int Id { get; init; }
public int CustomerId { get; } = customerId;
public DateTimeOffset CreatedAt { get; } = createdAt;
public OrderStatus Status { get; private set; }
public IReadOnlyList<OrderLine> Lines => _lines;
public decimal Total => _lines.Sum(line => line.Amount);
public bool IsShipped => Status is OrderStatus.Shipped;
public void AddLine(OrderLine line)
{
ArgumentNullException.ThrowIfNull(line);
_lines.Add(line);
}
public void Ship()
{
Status = OrderStatus.Shipped;
Shipped?.Invoke(this, new OrderShippedEventArgs(Id));
}
}Values in examples: customer and order IDs are small integers (7, 42), SKUs look like "SKU-1", money is decimal (9.99m), URLs use example.com, IP addresses use 192.0.2.x, and secrets are placeholders ("<from-secret-store>").
Terms are in alphabetical order. Definitions are written for this guide.
| Term | Definition |
|---|---|
.editorconfig |
A file of key = value settings read by Visual Studio, Rider, ReSharper and the .NET build. This guide ships one at config/.editorconfig. |
| Acronym | A word formed from initial letters (IO, Xml, Http). Two-letter acronyms are written fully upper case in PascalCase; longer ones capitalize only the first letter (NAM-010). |
| Allman style | Brace layout in which every opening and closing brace stands on its own line, aligned with the statement or declaration that owns it (FMT-020). |
| Analyzer | A component that inspects code during the build or in the IDE and reports diagnostics. The .NET SDK ships the code-style (IDE) and code-quality (CA) analyzers. |
| Analyzer-capable rule | A rule for which an IDE, CA or CS diagnostic exists, whether or not the rule is enforced through it. |
| Arrange-Act-Assert (AAA) | The three-block layout of a test: set up, perform one action, verify the outcome (TEST-021). |
| Awaitable type | A type that can be used with await: Task, Task<T>, ValueTask, ValueTask<T> and similar. |
| BCL | Base Class Library: the core .NET types such as System.String, System.Collections.Generic.List<T> and System.Threading.Tasks.Task. |
| BOM | Byte-order mark: the bytes at the start of a UTF-8 file that identify the encoding. C# files are saved as UTF-8 with BOM (FMT-010). |
| CA rule | A .NET code-quality analyzer rule with an ID such as CA1707 or CA2100. |
_camelCase |
camelCase with a leading underscore (_lineCount). Used for private, internal and private protected instance fields and mutable static fields, including [ThreadStatic] ones (_ordersPlaced, _depth), and accepted for protected and protected internal instance fields (NAM-200, NAM-203, NAM-210, NAM-212). |
| camelCase | Words joined without separators, first word lower case, later words capitalized (orderTotal). Used for parameters and locals, and preferred for local constants (maxAttempts, NAM-216). |
| Collection expression | C# 12 syntax that creates a collection from elements in brackets: [1, 2, 3], [], [..first, ..second] (VAR-531). |
| CS warning | A compiler diagnostic with an ID such as CS8618 (nullable) or CS1591 (missing XML comment). |
| Discard | The _ placeholder for a value you deliberately ignore (out _, _ = dictionary.Remove(key);). |
| Extension block | C# 14 syntax extension(Receiver receiver) { ... } inside a static class that declares extension members, including extension properties. |
| FDG | Framework Design Guidelines: Microsoft's naming and design guidance for public .NET APIs. |
field keyword |
C# 14 contextual keyword that refers to the compiler-generated backing field inside a property accessor (VAR-523). |
| File-scoped namespace | namespace Contoso.Orders; declared once at the top of a file, without braces (C# 10). Every file uses it, and IDE0161 reports a braced namespace block (FMT-060). |
| Hungarian notation | Encoding a type or scope in a name (strName, iCount, m_total). Banned (NAM-205). |
| IDE rule | A .NET code-style analyzer rule with an ID such as IDE0007 or IDE1006. Some run only in the IDE, never in dotnet build. |
| Implicit usings | The global using directives the SDK adds when ImplicitUsings is enabled (System, System.Linq, System.Threading.Tasks and others). |
| Manual rule | A rule no tool checks in the build; reviewers check it. Listed in the Manual review only table on page 15 (Tooling and Enforcement). |
| Naming rule | A set of dotnet_naming_symbols, dotnet_naming_style and dotnet_naming_rule keys that IDE1006 enforces. |
| NRT | Nullable reference types: the C# feature that tracks which references may be null and warns about unsafe use (VAR-050). |
| Null-forgiving operator | The postfix ! that tells the compiler an expression is not null; it has no runtime effect (VAR-053). |
| PascalCase | Words joined without separators, every word capitalized (OrderService). Used for types, members, constant fields, public fields and static readonly fields of every accessibility (OrderNumberFormat), and accepted for local constants and for protected instance fields (NAM-203, NAM-211, NAM-213, NAM-216). |
| Positional record | A record declared with a parameter list (record OrderLine(string Sku, int Quantity)); the parameters become public properties. |
| Primary constructor | C# 12 syntax that declares constructor parameters on the type itself: class OrderService(IOrderRepository repository) (LANG-012). |
| Raw string literal | A string delimited by three or more quotes ("""...""") that needs no escape sequences and can span lines. |
| ReSharper / Rider | JetBrains' Visual Studio extension and IDE. They read .editorconfig, including resharper_* keys. |
resharper_* key |
A JetBrains-specific .editorconfig property, used where ReSharper does not read the equivalent Roslyn key. |
| Roslyn | The .NET compiler platform; also used in this guide for the analyzers that ship with the SDK. |
| Rule ID | The stable identifier of a rule, a prefix and three digits (NAM-210). It is the rule's heading and anchor, is never renumbered or reused, and is cited in code reviews. |
s_ / t_ prefix |
Prefixes for static and thread-static fields used by Microsoft's identifier-naming page and dotnet/runtime. This guide does not use them: mutable static and thread-static fields take _ + camelCase, static readonly fields PascalCase (NAM-210, NAM-211, NAM-212). |
| SCREAMING_CASE | Upper-case words separated by underscores (MAX_ITEMS). Not used in C# names (NAM-206). |
| Security baseline | The # security-baseline block of the shipped .editorconfig that enables security analyzers no individual rule owns. |
| Severity | How a diagnostic is reported: error, warning, suggestion, silent or none. |
| StyleCop Analyzers | A third-party analyzer package (SA rules). This guide ships its reference commented out because no stable release supports C# 14. |
Target-typed new |
new() without a type name, where the type comes from the declaration (private readonly StringBuilder _buffer = new();). |
| Test double | An object that stands in for a dependency in a test: fake, stub or spy (TEST-012). |
| Top 25 | The 25 rules README lists first because they matter most in everyday code. |
var |
Implicitly typed local declaration; the compiler infers the type. Preferred for locals; an explicit type is accepted (VAR-010). |
The guide is maintained by hand and ships no generator or check, so these steps are the only safeguard against drift. Follow them whenever you add, change or retire a rule.
When a rule is added, changed or retired, update every table that mentions it in the same change:
- The rule index at the top of the rule's page.
- The naming cheat sheet on page 02, if the rule names an identifier kind.
- The Top 25 rules table on this page, if the rule is in it or enters it.
- The Manual review only table on page 15, if the rule's Enforced line says Manual.
- The row for the rule on page 90.
- The Security rules owned by other pages section on page 13, if the rule is linked from a secure-coding rule.
- The entry on page 92, if the rule cites a source key that does not exist yet.
- When you review page 13, re-check the SEC-053 iteration count against the current OWASP Password Storage Cheat Sheet.
Rule IDs are links from other pages, from the .editorconfig and from outside this guide. Treat them as permanent.
- An ID has the form
<PREFIX>-<NNN>with three digits. The anchor is the lower-case ID, for example#var-030. - Allocate IDs in groups of 10 by topic and insert new rules into the gaps. A new rule never shifts another rule's number.
- Never renumber an ID and never reuse one.
- To retire a rule, keep its
### <ID>heading and replace the body with**Retired** (<date>) — superseded by <link>or the reason. Remove its.editorconfigentries and remove its row from page 90. - To split a rule, the original ID keeps the dominant meaning and the split-off part gets a new ID in the same group. To merge rules, the surviving ID keeps its number and the other is retired with a pointer to it.
- To move a rule to another page, keep its ID only if the prefix still belongs to the target page. Otherwise retire it and write a new rule.
- Rule headings are exactly
### <ID>with no title, so anchors survive title edits.
The prefix and range for each page:
| Prefix | Page | Range |
|---|---|---|
FMT |
01 | all |
NAM |
02 | 001-099 |
NAM |
03 | 100-199 |
NAM |
04 | 200-299 |
VAR |
05 | 010-499 |
VAR |
06 | 500-999 |
LANG |
07 | all |
TYPE |
08 | all |
DOC |
09 | all |
ERR |
10 | all |
ASYNC |
11 | all |
TEST |
12 | all |
SEC |
13 | all |
DATA |
14 | all |
TOOL |
15 | all |
DI |
16 | all |
Every property in config/.editorconfig is traceable to the rule that owns it (TOOL-021).
- Put one comment line above each property that names the owning rule or rules:
# <RULE-ID>or# <RULE-ID>, <RULE-ID>. - Never write an inline comment after a value. Roslyn strips it, but other EditorConfig parsers do not promise to, so it can become part of the value (TOOL-021).
- Naming styles and symbol groups that several rules share go in a block headed
# shared. - Security analyzers that no single rule owns go in a block headed
# security-baseline. Each ID has its own severity line (TOOL-019). - Set every severity with
dotnet_diagnostic.<ID>.severity, and write option values without a:severitysuffix (TOOL-011). - When you retire a rule, remove its tagged lines.
Shape of tagged entries, taken from the shipped file:
# FMT-060
csharp_style_namespace_declarations = file_scoped
# FMT-060
dotnet_diagnostic.IDE0161.severity = warningA correct example (marked with a check mark) must compile and produce no warnings under the shipped configuration. Check each changed example by hand:
-
Create a scratch class library outside the folder of this guide and copy the four shipped configuration files into it. Give the project a PascalCase name: the template derives the namespace from it, and a lower-case name makes the generated file report
IDE1006.dotnet new classlib --framework net10.0 --no-restore --output ../scratch/Contoso.Orders cp config/.editorconfig ../scratch/Contoso.Orders/.editorconfig cp config/Directory.Build.props ../scratch/Contoso.Orders/Directory.Build.props cp config/global.json ../scratch/Contoso.Orders/global.json cp config/stylecop.json ../scratch/Contoso.Orders/stylecop.json
On a machine with no network, put a
nuget.confignext to the project that clears the sources (<clear />under bothpackageSourcesandauditSources), restore once withdotnet restore --configfile, and build with--no-restore. The scratch project has no package references, so the restore needs no feed. -
Paste the example into a class file, with the supporting types it uses.
-
Build. The shipped
Directory.Build.propsalready treats warnings as errors, so the build must report 0 warnings and 0 errors:dotnet build ../scratch/Contoso.Orders
-
For an incorrect example that a diagnostic enforces, build it the same way. The diagnostic named in the rule's Enforced line must appear on a line that carries a
// <what is wrong>comment. -
Re-check any rule whose example uses a C# 12 or later feature with the callout still in place.
If an example needs a suppression to build, the rule is not enforced the way its page claims. Fix the page or the configuration, not the example.