agentleFS
Roly67Roly67/cc-skills/dotnet-coding-standards/SKILL.md

dotnet-coding-standards

Skill1 starsChanged 11 months agoMITView on GitHub

.NET coding standards and patterns. Use when: creating new .NET solutions, writing C# classes/services/controllers, setting up Serilog logging, configuring Sentry error tracking, reviewing pull requests, checking code coverage, fixing StyleCop warnings, adding unit tests, or scaffolding Web API/Console/Worker/Blazor projects. Covers Clean Architecture, async/await patterns, ConfigureAwait usage, and CI/CD pipeline configuration. Apply to all .cs and .csproj files.

1 other project uses a version of this.

Adopted by

Most recently taken up by

  • Other versions1 project uses a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 1

    1. Dannykkh/skill-olympus★ 9same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repositoryOne other file it gives its agents.

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 4 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before committing: Run the PR Review Checklist

    line 60
  2. Distinctive:

    Every class with business logic MUST have corresponding unit tests with 80%+ coverage.

    line 107
  3. Distinctive:

    If you genuinely cannot follow a standard (e.g., third-party library conflict):

    line 309
  4. Distinctive:

    Never: use pragma suppressions as an escape hatch.

    line 316
  5. Very specific:

    Import .editorconfig from solution root

    line 324
  6. Very specific:

    Add to settings.json: "omnisharp.enableEditorConfigSupport": true

    line 335

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

.NET Coding Standards

Comprehensive coding standards for .NET projects following Clean Architecture principles.

Customization

This skill uses placeholders for company-specific values. Replace these throughout:

PlaceholderDescriptionExample
{CompanyName}Your company/organization nameAcme, Contoso
{ProjectName}Your project nameOrderApi, PaymentService
{email}Support/contact emailsupport@example.com
{domain}Your company domainexample.com

🚀 New Developer Quick Start

  1. Clone the repo and run dotnet restore
  2. Read the project's README.md (every project has one)
  3. Check you have .NET 10 SDK installed
  4. Run dotnet build — must complete with zero warnings
  5. Run dotnet test — must have 80%+ coverage
  6. Before committing: Run the PR Review Checklist

First task? Start with the New Solution Checklist.


Quick Reference

RequirementRule
CopyrightEvery .cs file starts with the copyright header
NamespacesFile-scoped: {CompanyName}.[ProjectName].[Layer].[Feature]
DocumentationAll public members require XML docs
Null safety?? throw new ArgumentNullException(nameof(param)) in constructors
Field accessAlways use this. prefix for instance members
Build ruleZero warnings allowed (TreatWarningsAsErrors=true)
Framework.NET 10, nullable reference types enabled
StyleCopCentralized config, NO pragma suppressions allowed
C# versionC# 13 features enabled (with .NET 10)
TestingAll functional classes must have unit tests
CoverageMinimum 80% code coverage required
READMEEvery solution must have comprehensive README.md
ConfigureAwaitUse ConfigureAwait(false) in library/infrastructure code
LoggingSerilog in all host processes (overrides Microsoft logging)
ExceptionsSentry for exception tracking in all host processes

❌ Critical Rules (Non-Negotiable)

Never Use Pragma Suppressions

// ❌ FORBIDDEN
#pragma warning disable SA1600
public class MyClass { }
#pragma warning restore SA1600

// ✅ CORRECT - Fix the actual issue
/// <summary>
/// Provides functionality for processing data.
/// </summary>
public class MyClass { }

Never Skip Unit Tests for Functional Classes

Every class with business logic MUST have corresponding unit tests with 80%+ coverage.

Never Use Microsoft.Extensions.Logging Config in Hosts

Serilog configuration takes precedence. See Serilog Standards.


📁 Detailed Documentation

By Project Type

Project TypeGuide
Web APIproject-types/web-api.md
Console Applicationproject-types/console-app.md
Class Libraryproject-types/class-library.md
Worker Serviceproject-types/worker-service.md
Blazorproject-types/blazor.md

Standards & Patterns

TopicGuide
Clean Architecturestandards/clean-architecture.md
CQRS & MediatRstandards/cqrs-mediatr.md
Domain Designstandards/domain-design.md
Error Handlingstandards/error-handling.md
StyleCop & Code Stylestandards/stylecop.md
Nullability & Annotationsstandards/nullability-annotations.md
Serilog Loggingstandards/logging-serilog.md
Sentry Error Trackingstandards/error-tracking-sentry.md
Testing & Coveragestandards/testing-coverage.md
Async & ConfigureAwaitstandards/async-configureawait.md
Documentation & READMEstandards/documentation.md
Securitystandards/security.md
API Designstandards/api-design.md
Performancestandards/performance.md
Dependency Injectionstandards/dependency-injection.md
Git Workflowstandards/git-workflow.md

Templates (Copy-Paste Ready)

TemplateFile
README.mdtemplates/README-template.md
appsettings.jsontemplates/appsettings-template.json
Directory.Build.propstemplates/Directory.Build.props
stylecop.jsontemplates/stylecop.json
.editorconfigtemplates/editorconfig.txt
coverlet.runsettingstemplates/coverlet.runsettings
GitHub Actions CItemplates/github-actions-ci.yml

Checklists

ChecklistFile
New Solution Setupchecklists/new-solution-checklist.md
PR Reviewchecklists/pr-review-checklist.md

IDE Snippets

IDELocation
VS Codesnippets/vscode/csharp.json
Visual Studiosnippets/visualstudio/cs-snippets.snippet
JetBrains Ridersnippets/rider/CodingStandards.DotSettings
Installation Guidesnippets/README.md

Common Mistakes to Avoid

Logging

MistakeWhy It's WrongCorrect Approach
logger.LogInformation($"User {userId}")Loses structure, poor performancelogger.LogInformation("User {UserId}", userId)
Using ILogger directly in class libraryCouples to implementationUse ILogger<T> from abstractions
catch (Exception) { }Swallows errors silentlyLog and rethrow, or handle specifically
Microsoft logging config in appsettingsIgnored when Serilog is usedUse Serilog section only

Async/Await

MistakeWhy It's WrongCorrect Approach
Task.Run(() => AsyncMethod())Wastes thread pool threadawait AsyncMethod()
.Result or .Wait()Deadlock riskAlways await
Missing ConfigureAwait(false) in libraryCaptures unnecessary sync contextAdd ConfigureAwait(false)
ConfigureAwait(false) in controllerLoses HttpContextDon't use in controllers
Missing Async suffixNaming inconsistencyAll async methods end with Async

Testing

MistakeWhy It's WrongCorrect Approach
No tests for service classUntested business logicEvery functional class needs tests
Testing implementation detailsBrittle testsTest behavior, not internals
[Fact] public void Test1()Unclear purpose[Fact] public void MethodName_Scenario_ExpectedResult()
Not testing exception casesIncomplete coverageTest happy path AND error paths

StyleCop

MistakeWhy It's WrongCorrect Approach
#pragma warning disableHides technical debtFix the actual issue
_fieldNameNon-standard for this codebasethis.fieldName
Missing XML docsSA1600 violationDocument all public members
Block-scoped namespaceSA1513 violationUse file-scoped namespace X;

Decision Flowcharts

Should I Use ConfigureAwait(false)?

Is this code in a Controller, Razor Page, or Blazor component?
├── YES → Do NOT use ConfigureAwait(false)
└── NO → Does this code access HttpContext, User, or UI elements?
    ├── YES → Do NOT use ConfigureAwait(false)
    └── NO → USE ConfigureAwait(false) ✓

What Log Level Should I Use?

Is this an unhandled exception or app crash?
├── YES → LogCritical (Fatal)
└── NO → Did an operation fail?
    ├── YES → LogError
    └── NO → Is something unexpected but handled?
        ├── YES → LogWarning
        └── NO → Is this a significant business event?
            ├── YES → LogInformation
            └── NO → Is this useful for debugging?
                ├── YES → LogDebug
                └── NO → LogTrace (or don't log)

Do I Need a Unit Test for This Class?

Does this class contain business logic or behavior?
├── YES → Unit test REQUIRED ✓
└── NO → Is this a DTO, model, or configuration class?
    ├── YES → Unit test optional (data-only)
    └── NO → Is this auto-generated code?
        ├── YES → Unit test not needed
        └── NO → Is this startup/Program.cs?
            ├── YES → Integration test instead
            └── NO → Probably needs a unit test ✓

Package Versions

PackageMinimumRecommendedNotes
.NET SDK10.010.0Required
Serilog4.0.04.0.0
Serilog.AspNetCore8.0.08.0.0For Web API
Sentry4.0.04.3.0
Sentry.Serilog4.0.04.3.0
StyleCop.Analyzers1.2.0-beta.5561.2.0-beta.556Beta required for C#13 support
FluentAssertions6.0.06.12.0
Moq4.18.04.20.70
xUnit2.6.02.6.4
Coverlet6.0.06.0.0

Quick Commands

# Build with zero warnings
dotnet build --warnaserrors

# Run all tests with coverage
dotnet test --collect:"XPlat Code Coverage" --settings coverlet.runsettings

# Generate HTML coverage report
reportgenerator -reports:./TestResults/**/coverage.cobertura.xml -targetdir:./coverage -reporttypes:Html

# Find StyleCop violations
dotnet build 2>&1 | grep -E "SA[0-9]{4}"

# Find pragma suppressions (should return nothing)
grep -r "#pragma warning disable" --include="*.cs" src/

# Find missing ConfigureAwait in Infrastructure
grep -r "await.*;" --include="*.cs" src/Infrastructure/ | grep -v "ConfigureAwait(false)"

# Find Microsoft logging config (should not exist in hosts)
grep -r '"Logging"' --include="appsettings*.json" src/

Exception Process

If you genuinely cannot follow a standard (e.g., third-party library conflict):

  1. Document the exception in code: // STANDARDS-EXCEPTION: [reason]
  2. Create a GitHub issue linking to the code
  3. Get tech lead approval
  4. Add to project's docs/EXCEPTIONS.md file

Never use pragma suppressions as an escape hatch.


IDE Setup

Visual Studio 2022

  1. Tools → Options → Text Editor → C# → Code Style
  2. Import .editorconfig from solution root
  3. Enable "Run code analysis on build"

JetBrains Rider

  1. Settings → Editor → Code Style → C#
  2. Import from .editorconfig
  3. Enable StyleCop inspections in Inspections settings

VS Code

  1. Install C# Dev Kit extension
  2. Install "EditorConfig for VS Code" extension
  3. Add to settings.json: "omnisharp.enableEditorConfigSupport": true

Glossary

TermDefinition
AggregateA cluster of domain objects treated as a single unit with a root entity
BreadcrumbSentry term for contextual events leading up to an error
CanBeNullJetBrains annotation indicating a parameter or return value may be null
Clean ArchitectureLayered architecture with Domain at center, dependencies pointing inward
ConfigureAwait(false)Tells async/await not to capture the synchronization context
ContractAnnotationJetBrains annotation for specifying method behavior based on input/output nullability
CQRSCommand Query Responsibility Segregation — separating read and write operations
Domain EventA record of something significant that happened in the domain
Host ProcessExecutable project (API, Console, Worker) that runs the application
MediatRIn-process messaging library for implementing CQRS pattern
NotNullJetBrains annotation indicating a parameter or return value cannot be null
NRTNullable Reference Types — C# compiler feature for null safety
PureJetBrains annotation marking methods with no side effects
Result PatternAlternative to exceptions for expected failures, returning success/failure with value
Structured LoggingLogging with named placeholders {PropertyName} that preserve data types
SUTSystem Under Test — the class being tested in a unit test
Value ObjectImmutable object defined by its attributes rather than identity

Changelog

  • 2.4.0 (2026-02-20): Audit & update — added globs/triggers to frontmatter, updated C# 12→13 references, fixed StyleCop version notes, added Seq apiKey guidance
  • 2.3.0 (2026-01-11): Added Nullability & Annotations standards (JetBrains.Annotations)
  • 2.2.0 (2026-01-11): Added Clean Architecture, CQRS/MediatR, Domain Design, Error Handling standards
  • 2.1.0 (2026-01-10): Added Serilog, Sentry, ConfigureAwait standards; multi-file structure
  • 2.0.0 (2025-12-01): Extended to multiple project types (Console, Worker, Blazor)
  • 1.0.0 (2025-10-15): Initial Web API standards

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.