csharp-idioms
Skill157 starsChanged 3 months agoMITView on GitHub
Modern C# (10+/.NET) coding idioms: nullable reference types, records, pattern matching, async/await with CancellationTokens, LINQ performance, and DI. Use when writing, modifying, or reviewing C# application code or domain models. Pair with dotnet-idioms for framework APIs.
In this repository59 other files it gives its agents.
- github-pages/agents.mdAGENTS.md
- adrSkill
- agent-protocolsSkill
- angular-idiomsSkill
- api-documentationSkill
- axum-idiomsSkill
- browser-automationSkill
- chaos-testingSkill
- ci-cdSkill
- cli-developmentSkill
- code-auditSkill
- code-reviewSkill
- cpp-idiomsSkill
- data-engineeringSkill
- debugging-protocolSkill
- django-idiomsSkill
- dotnet-idiomsSkill
- elixir-idiomsSkill
- embedded-systemsSkill
- feature-flagsSkill
- flutter-idiomsSkill
- frontend-designSkill
- git-commit-integritySkill
- go-idiomsSkill
- guardrailsSkill
- hono-idiomsSkill
- incident-responseSkill
- java-idiomsSkill
- javascript-idiomsSkill
- kotlin-idiomsSkill
- laravel-idiomsSkill
- logging-implementationSkill
- ml-engineeringSkill
- mobile-designSkill
- mobile-testingSkill
- nextjs-idiomsSkill
- parallel-dispatchSkill
- payment-integrationSkill
- perf-optimizationSkill
- php-idiomsSkill
- postgres-idiomsSkill
- python-idiomsSkill
- rails-idiomsSkill
- react-idiomsSkill
- refactoring-patternsSkill
- research-methodologySkill
- ruby-idiomsSkill
- rust-idiomsSkill
- security-auditSkill
- sequential-thinkingSkill
- spring-boot-idiomsSkill
- sql-idiomsSkill
- structured-specSkill
- supply-chain-securitySkill
- swift-idiomsSkill
- testability-patternsSkill
- testing-strategySkill
- typescript-idiomsSkill
- vue-idiomsSkill
The file
Files
C# Idioms and Patterns
C# rewards type safety, LINQ expressiveness, and async-first design. Modern C# (10+/.NET 6+) favors records, nullable reference types, and minimal APIs. Idiomatic C# = clean, async-aware, framework-integrated.
Scope: C# coding idioms. Test naming: .agents/rules/testing-strategy.md. Logging:
@.agents/skills/logging-implementation/SKILL.md.
Modern C# Features (10+)
- Nullable reference types — always enabled:
// ✅ Explicit nullability public Task? FindById(string id) { ... } public Task GetById(string id) { ... } // never returns null — throws // In .csproj: <Nullable>enable</Nullable> - Records for immutable data:
public record CreateTaskRequest(string Title, Priority Priority); public record TaskResponse(string Id, string Title, DateTime CreatedAt); - Pattern matching:
return result switch { Success(var task) => Ok(task), NotFound(var id) => NotFound($"Task {id} not found"), ValidationError(var errors) => BadRequest(errors), _ => StatusCode(500) }; requiredandinitfor safe construction:public class AppConfig { public required string DatabaseUrl { get; init; } public required string ApiKey { get; init; } public int MaxRetries { get; init; } = 3; }
Error Handling
- Result pattern over exceptions for expected failures:
public record Result<T> { public T? Value { get; init; } public string? Error { get; init; } public bool IsSuccess => Error is null; public static Result<T> Ok(T value) => new() { Value = value }; public static Result<T> Fail(string error) => new() { Error = error }; } - Domain exceptions for unexpected failures — never raw
Exception. - Never
catch (Exception)without re-throw or specific handling.
Async/Await
- Async all the way — never
.Resultor.Wait()on tasks:// ✅ Async pipeline public async Task<Task> GetTaskAsync(string id, CancellationToken ct) { return await _storage.GetByIdAsync(id, ct) ?? throw new NotFoundException("Task", id); } // ❌ Sync-over-async — deadlock risk var task = _storage.GetByIdAsync(id).Result; - Always accept
CancellationTokenon async methods. ConfigureAwait(false)in library code only.
Dependency Injection
- Constructor injection — no property or method injection:
public class TaskService { private readonly ITaskStorage _storage; private readonly ILogger<TaskService> _logger; public TaskService(ITaskStorage storage, ILogger<TaskService> logger) { _storage = storage; _logger = logger; } } - Register in DI container — never
newa service:builder.Services.AddScoped<ITaskStorage, PostgresTaskStorage>(); builder.Services.AddScoped<TaskService>();
LINQ
- Prefer method syntax for complex queries, query syntax for joins:
var active = tasks .Where(t => t.IsActive) .OrderByDescending(t => t.Priority) .Select(t => new TaskSummary(t.Id, t.Title)); - Never mutate collections during LINQ iteration.
Naming
- PascalCase for classes, methods, properties, events, namespaces.
- camelCase for parameters, local variables.
_camelCasefor private fields (prefix underscore).Iprefix for interfaces:ITaskStorage.Asyncsuffix for async methods:GetByIdAsync.
Testing
- xUnit + FluentAssertions:
[Fact] public async Task GetTask_ReturnsTask_WhenExists() { var result = await _service.GetTaskAsync("task-1", CancellationToken.None); result.Should().NotBeNull(); result.Title.Should().Be("Test Task"); } [Theory]for parameterized tests:[Theory] [InlineData("low", 1)] [InlineData("medium", 5)] [InlineData("high", 10)] public void PriorityScore_MapsCorrectly(string priority, int expected) { Priority.Score(priority).Should().Be(expected); }- NSubstitute or Moq for mocking.
Formatting and Static Analysis
| Tool | Purpose | Command |
dotnet format | Canonical formatting | dotnet format |
| Roslyn Analyzers | Compile-time analysis | Built-in |
SonarAnalyzer | Comprehensive analysis | NuGet package |
dotnet-outdated | Dependency freshness | dotnet-outdated |
dotnet list package --vulnerable | CVE scanning | Built-in (.NET 8+) |
Related
- Code Idioms and Conventions .agents/rules/code-idioms-and-conventions.md
- Testing Strategy .agents/rules/testing-strategy.md
- Error Handling Principles .agents/rules/error-handling-principles.md
- Dependency Management Principles @.agents/rules/dependency-management-principles.md
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
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.

