StyleCop Rules — Code Style the Build Enforces
Three people work on ReadingRoom. One puts using lines inside the namespace, one outside; one documents every method, one never does. Code review turns into a style debate. StyleCop ends the debate by letting the build check style, the same way the compiler checks types.
The rule
Agree on style once, in config; let the build point out breaks.
StyleCop.Analyzers is a NuGet package of Roslyn analyzers — small checks that run inside the C# compiler. Each rule has an id starting with SA and reports a diagnostic while you type and when you build.
dotnet add package StyleCop.AnalyzersRules fall into families: spacing, readability, ordering (for example, where using directives go), naming, maintainability, layout (braces and blank lines) and documentation. A few examples of what they catch:
- a public member with no XML documentation comment (
SA1600) - a file without the agreed header comment (
SA1633) - a field name that breaks the naming convention
You tune rules in .editorconfig, which the whole team shares:
[*.cs]
dotnet_diagnostic.SA1600.severity = none # we do not document every member
dotnet_diagnostic.SA1633.severity = none # no file headersA stylecop.json file holds finer options, such as the company name for headers. Add <TreatWarningsAsErrors>true</TreatWarningsAsErrors> to the project if style breaks should fail the build outright. dotnet format can fix many issues automatically.
The shortcut
When a warning appears, read its id before touching code. SA means a StyleCop style rule; CS means the compiler itself. Then ask: is the rule wrong for us (change .editorconfig, once, for everyone) or is the code wrong (fix the code)?
Read the id
The build says
SA1101: Prefix local calls with this. SA means it is StyleCop, not a compile error.
The trap: silencing a rule with a #pragma in one file. That hides the disagreement instead of settling it.
Drills
Answer fast — trust the rule.
A build shows SA1600. Where does it come from?
Where should the team turn a StyleCop rule off for the whole repository?
How do you add StyleCop to a project?
What does setting TreatWarningsAsErrors to true do to style warnings?
Remember
- Agree on style once, in config; let the build point out breaks.
- SA ids are StyleCop, CS ids are the compiler; read the id first.
- Tune rules in
.editorconfig, not with scattered pragmas.
