How C# is written — the house style every .NET repository enforces. Use when writing, generating or reviewing any C# code: declarations, object creation, collections, braces, parameter and argument lists, naming, modifiers, null checks, comments, file encoding and line endings, or when a build fails on a style rule. It encodes: explicit types (no var, no target-typed new(), no collection expressions) as a stated departure from Microsoft's defaults, braces always, a 120-column width with all-o...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Code Style Dotnet?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/jorgecostamacia-code-style-dotnet-code-harness)
---
name: code-style-dotnet
description: >-
How C# is written — the house style every .NET repository enforces. Use when
writing, generating or reviewing any C# code: declarations, object
creation, collections, braces, parameter and argument lists, naming,
modifiers, null checks, comments, file encoding and line endings, or when
a build fails on a style rule. It encodes: explicit types (no var, no
target-typed new(), no collection expressions) as a stated departure from
Microsoft's defaults, braces always, a 120-column width with all-or-nothing
wrapping and growing lists kept vertical, the naming and modifier
conventions, `is null` outside expression trees, comments only where the
code cannot speak, CRLF, `dotnet format` before committing, and the strict
gates that make all of it a build error.
---
# C# style
The style is **enforced, not suggested**: `.editorconfig` + `EnforceCodeStyleInBuild` + `TreatWarningsAsErrors` turn a violation into a build error, and `dotnet format --verify-no-changes` must exit 0. The sections below spell out what no analyzer catches. That part is the job of whoever writes the code, generators included.
## Explicit types — a deliberate departure from Microsoft's defaults
Microsoft's own C# conventions recommend `var` where the type is evident, the concise `new()` where the variable's type is already written, and collection expressions `[…]` for every collection. This style turns the three off, because people read the code without an IDE. In a diff, a review or a generated file, a spelled-out type is the only type the reader gets. The `.editorconfig` analyzer turns off `var` (`csharp_style_var_* = false:warning`). A CI grep catches `new()` and `new[]`: the `false` knobs only stop the IDE from generating them, and they don't flag what is already written. A second grep catches `[…]`, because `dotnet_style_prefer_collection_expression = false` flags nothing either. Everything else about layout follows those same conventions: Allman braces, four spaces, one statement and one declaration per line, a break before a binary operator.
- **No `var`.** `Pedidos aggregate = …`, `List<Command> commands = …`.
- **No target-typed `new()`** — `new PedidosExtractService(context)`, never `new(context)`. The analyzer can't flag it; a CI grep guard does:
```bash
grep -rnE '\bnew\(|new\[\]' --include='*.cs' --exclude-dir=obj --exclude-dir=bin src test | grep -vE '\bwhere\b[^=]*\bnew\(\)'
```
(`new()` in a `where` constraint — `where T : new()`, `where T : class, new()` — is the one allowed form.)
- **No collection expressions** `[]`, no implicit `new[] { … }`: `new List<string>()`, `new string[] { "a", "b" }`, `Array.Empty<T>()`, `ImmutableList.Create(...)`. The first grep catches `new[]`. A second one catches `[…]` in two shapes. The first shape is a `[` opened right after `=`, `=>`, `return`, `(` or `,` and closed before `;`, `,` or `)`. The second is a `[` left at the end of an assignment or alone on its line (a multi-line one, Allman style). Attributes, indexers, array types and list patterns never match it:
```bash
grep -rnE '(=|=>|return|\(|,)[[:space:]]*\[[^]]*\][[:space:]]*[;,)]|(=|=>|return)[[:space:]]*\[[[:space:]]*$|^[[:space:]]*\[[[:space:]]*$' --include='*.cs' --exclude-dir=obj --exclude-dir=bin src test
```
## Shape
- **Braces always**, opening brace on its own line. An empty body may close on the same line (`: base(value) { }`, `private Pedidos() { }`). An empty type body is the `;` form (`public sealed class PostgreSqlCollection : ICollectionFixture<PostgreSqlFixture>;`).
- **A blank line before `return`** (unless it is the block's only statement).
- **120 columns is the reference width, and a list is all on one line or all vertical — never mixed.** A vertical list has one element per line, `) : base(…)` on its own line, and the break **before** a binary operator. The kind of a list decides whether it goes vertical, so a reviewer can check it, in `src/` and `test/` alike. A seeded sixteen-argument `Create(…)` on one line in a test is exactly where someone inserts the next field by counting nulls:
| List | Rule |
| --- | --- |
| A method or constructor **declaration** with two or more parameters | **Vertical always**, even when it fits — except a pair that is the thing itself (a range's `start` and `end`, a context's `services` and `configuration`) |
| The **construction** of a message, event, exception or domain object: `new …Event(…)`, an exception's `) : base(…)`, `Create(…)` / `From(…)` | **Vertical always**, even when it fits: these are the lists that grow, so adding a field changes one line |
| Any other call, initializer or boolean chain | **By width**: one line when it fits in 120, vertical when it doesn't. This includes the base calls of infrastructure (a converter's, a worker's) and fixed metadata that no field ever joins: a bus message's `) : base(aggregateId, aggregateCorrelationId, aggregateOccurredAt, aggregateConsumers)`, the tracing ids of an HTTP request or response. `Send(commands, transport, token)` and `PushProperty(name, value)` stay on their line. |
If a **one-parameter** declaration does not fit, break it before its `=>` (or its `: base(…)`) and keep the parameter on its line. One parameter is not a list: only a signature that still overflows puts the parameter on a line of its own. A single expression with no natural break (a route constant, an interpolated string) may exceed the width. **Comments follow the same width**: split a `///` or `//` line over 120 at a word boundary, with the same prefix and indentation. The content of a `<code>` block is the exception. No tool enforces any of this, because `dotnet format` doesn't wrap. So it is the job of whoever writes the code, generators included. CSharpier is the mechanical version, but it collapses whatever fits its width: adopt it only if you accept that.
- Expression-bodied members (`=>`) for one-liners; a block when there is more than one statement.
- Prefer a `using` over full qualification; `global using`s only for what every file needs.
## Enforced by the analyzers
The `.editorconfig` turns these into build errors. This section states them only so that a generator writes them right the first time. Use **file-scoped namespaces**, and the namespace **matches the folder**. Put the `using`s **outside** the namespace, `System` first. Give every member an **explicit accessibility**. A field that is never reassigned is **`readonly`**. **No primary constructors** is a rule too, but nothing enforces it: `csharp_style_prefer_primary_constructors = false` only stops the IDE from suggesting them. A reviewer catches them, until the grep learns to.
## Names
- PascalCase for types and members, **camelCase** for locals and parameters, **`_camelCase`** for private fields, `I`-prefixed interfaces.
- Lambdas: `v =>` in validators (nested `v2`), `e =>` in query predicates.
- Application locals are **`aggregate` / `aggregates`** — the word the domain models — and the arriving data is `payload`.
- Domain concepts in the business's language, technical suffixes in English (`PedidosLoadService`, `PedidosValidator`).
## Modifiers
- Messages: `public sealed record`. Value objects: `internal sealed record`. Aggregates, services, handlers, validators: `internal sealed class`. The `DbContext`: `internal class`, not sealed (see `efcore-dotnet`). Composition contexts: `public static class` (the module's) / `internal static class` (its layers').
- Modifier order follows the `.editorconfig` (`public, private, protected, internal, file, static, … new, …, override, readonly, …, async`).
## Null and booleans
- **`is null` / `is not null`** and **`!flag`** — not `== null`, `!= null`, `== false`.
- The exception: inside an **expression tree** (an EF Core predicate) a pattern is `CS8122` — there it is `!= null`.
- Nullable reference types are on. Use `!` (null-forgiving) only where the code proves non-null and the compiler can't see it. The reason must be visible in the surrounding lines.
## Comments and documentation
- A comment says what the code **cannot**: a non-obvious constraint, why you rejected the obvious approach, what breaks if this changes. A comment restating the line above it is worse than none — it reads as authoritative and rots.
- No commented-out code — except a deliberately disabled registration that an operator uncomments by hand, with the comment saying when and why.
- **Doc XML only where there are outside consumers**: a library ships it (`GenerateDocumentationFile`, `CS1591` an error); an application doesn't, and neither does a contracts package, whose consumers are the organization's own services: `CS1591` would only buy comments that restate the names they sit on.
- Comments, docs and commit messages in English.
## Files
- **UTF-8 and a final newline for every text file** (`[*]` in `.editorconfig`). Trim trailing whitespace, except where the format gives it meaning (`[*.md]`, where two spaces are a line break).
- **CRLF for `.cs`**, pinned twice, for two readers. `.editorconfig` (`[*.cs] end_of_line = crlf`) is the hook for `dotnet format`. If a shell tool wrote a `.cs` with LF, or left it with mixed endings, the next `dotnet format` run rewrites it to one ending. That keeps the editor quiet on Windows. `.gitattributes` (`*.cs text diff=csharp eol=crlf`) is for the checkout: git stores LF. Without the attribute, a Linux CI runner checks the files out LF, and `dotnet format --verify-no-changes` flags every line (`ENDOFLINE`) of code that is fine. Every other file is git's: `* text=auto` stores LF and checks out the platform's ending. An attribute keeps `.sh` LF and `.cmd` / `.ps1` CRLF, and nobody normalizes line endings by hand.
- C# indented with 4 spaces; `.csproj` / `.props` / `.targets` with **tabs**.
- **Run `dotnet format <solution>` before every commit** — using order, whitespace, charset, line endings. It is the normalizer, not a check: `--verify-no-changes` is the check-only form, the one CI runs after the build. On a Linux runner it needs the `.gitattributes` line above.
## The gates
- `EnforceCodeStyleInBuild`, `TreatWarningsAsErrors`, `AnalysisLevel latest`, `Nullable enable` — the build has **zero warnings**, and stays that way.
- **No `NoWarn`, no `#pragma warning disable`.** Fix the warning, or change the rule for the whole repository in `.editorconfig` with a reason. Never silence it at one site.