Csharp Style Guide
Scope Boundaries
- Use this skill when the task matches the trigger condition described in
description.
- Do not use this skill when the primary task falls outside this skill's domain.
Use this skill to write and review C# code that is safe, maintainable, and production-ready.
Trigger And Co-activation Reference
- If available, use
references/trigger-matrix.md as the canonical trigger/co-activation matrix.
- If available, resolve style-guide activation from changed files with
python3 scripts/resolve_style_guides.py <changed-path>....
- If available, validate trigger matrix consistency with
python3 scripts/validate_trigger_matrix_sync.py.
Quality Gate Command Reference
- If available, use
references/quality-gate-command-matrix.md for CI check-only vs local autofix mapping.
Quick Start Snippets
Startup options validation (fail fast)
builder.Services
.AddOptions<MyServiceOptions>()
.Bind(builder.Configuration.GetSection("MyService"))
.ValidateDataAnnotations()
.ValidateOnStart();
CancellationToken propagation
public async Task<OrderDto> GetOrderAsync(Guid orderId, CancellationToken cancellationToken)
{
var entity = await _repository.FindByIdAsync(orderId, cancellationToken);
return entity is null ? throw new NotFoundException(orderId) : Map(entity);
}
Specific exception handling at boundary
try
{
await _publisher.PublishAsync(message, cancellationToken);
}
catch (TimeoutException ex)
{
_logger.LogWarning(ex, "Publish timeout for message {MessageId}", message.Id);
throw new TransientDependencyException("Publish timed out", ex);
}
Architecture And Module Boundaries
- Keep dependency direction explicit (domain -> application -> infrastructure).
- Isolate side effects (I/O, DB, network) behind interfaces.
- Keep controllers/handlers thin; move business rules into domain/application services.
- Split classes by responsibility; avoid god classes.
Naming And Code Structure
- Use PascalCase for types/methods/properties, camelCase for locals/parameters.
- Use intent-revealing names instead of implementation detail names.
- Keep methods focused; extract private helpers for complex branches.
- Replace magic numbers with named constants including units (
RetryDelayMilliseconds).
Types And Data Modeling
- Enable nullable reference types and treat warnings as actionable.
- Prefer explicit DTO/value objects over
dynamic or loosely typed dictionaries.
- Use
record for immutable data where semantics fit.
- Define explicit boundary contracts for request/response models.
Error Handling And Async Behavior
- Throw specific exception types with actionable context.
- Catch exceptions at boundaries and map intentionally (retry/log/translate/rethrow).
- Avoid blanket
catch (Exception) unless rethrowing after required handling.
- Pass
CancellationToken through async chains.
- Avoid sync-over-async (
.Result, .Wait()).
Configuration And Environment
- Bind configuration to typed options and validate at startup.
- Fail startup when required environment variables/config are missing.
- Do not add silent fallback defaults for required configuration.
- Keep secrets in secret stores, not source code.
Security And Compliance
- Validate/sanitize external input.
- Use parameterized queries/ORM bindings; never concatenate SQL.
- Enforce authn/authz close to entry points.
- Avoid logging sensitive data (tokens, passwords, PII).
Performance And Resource Usage
- Profile before micro-optimization.
- Use streaming/pagination for large datasets.
- Reuse outbound clients (
IHttpClientFactory).
- Respect cancellation and timeout policies for outbound I/O.
Testing And Verification
- Add unit tests for business logic and integration tests for boundaries.
- Cover nullability, cancellation, timeout, invalid payloads, and concurrency edges.
- Add regression tests for each fixed defect.
- Document manual verification when automation is infeasible.
Observability And Operations
- Use structured logs with correlation/request IDs.
- Emit metrics for latency, errors, and dependency calls.
- Map failures to stable operational signals (status/error codes).
- Ensure telemetry supports incident triage.
CI Required Quality Gates (check-only)
- Run
dotnet format --verify-no-changes.
- Run
dotnet build -warnaserror.
- Run
dotnet test.
- Reject changes that hide failures with broad fallbacks.
Optional Autofix Commands (local)
- Run
dotnet format.
1---2name: csharp-style-guide3description: Style, review, and refactoring standards for C#/.NET codebases. Trigger when `.cs`, `.csproj`, `.sln`, `.props`, `.targets`, or `.razor` artifacts are created, modified, or reviewed and C#-specific quality rules (naming, nullability, async patterns, API design consistency) must be enforced. Do not use for Java/Kotlin or JavaScript/TypeScript style concerns unless C# artifacts are also changed. In multi-language pull requests, run together with other applicable `*-style-guide` skills.4---56# Csharp Style Guide78## Scope Boundaries9- Use this skill when the task matches the trigger condition described in `description`.10- Do not use this skill when the primary task falls outside this skill's domain.1112Use this skill to write and review C# code that is safe, maintainable, and production-ready.1314## Trigger And Co-activation Reference1516- If available, use `references/trigger-matrix.md` as the canonical trigger/co-activation matrix.17- If available, resolve style-guide activation from changed files with `python3 scripts/resolve_style_guides.py <changed-path>...`.18- If available, validate trigger matrix consistency with `python3 scripts/validate_trigger_matrix_sync.py`.1920## Quality Gate Command Reference2122- If available, use `references/quality-gate-command-matrix.md` for CI check-only vs local autofix mapping.2324## Quick Start Snippets2526### Startup options validation (fail fast)2728```csharp29builder.Services30 .AddOptions<MyServiceOptions>()31 .Bind(builder.Configuration.GetSection("MyService"))32 .ValidateDataAnnotations()33 .ValidateOnStart();34```3536### CancellationToken propagation3738```csharp39public async Task<OrderDto> GetOrderAsync(Guid orderId, CancellationToken cancellationToken)40{41 var entity = await _repository.FindByIdAsync(orderId, cancellationToken);42 return entity is null ? throw new NotFoundException(orderId) : Map(entity);43}44```4546### Specific exception handling at boundary4748```csharp49try50{51 await _publisher.PublishAsync(message, cancellationToken);52}53catch (TimeoutException ex)54{55 _logger.LogWarning(ex, "Publish timeout for message {MessageId}", message.Id);56 throw new TransientDependencyException("Publish timed out", ex);57}58```5960## Architecture And Module Boundaries61621. Keep dependency direction explicit (domain -> application -> infrastructure).632. Isolate side effects (I/O, DB, network) behind interfaces.643. Keep controllers/handlers thin; move business rules into domain/application services.654. Split classes by responsibility; avoid god classes.6667## Naming And Code Structure68691. Use PascalCase for types/methods/properties, camelCase for locals/parameters.702. Use intent-revealing names instead of implementation detail names.713. Keep methods focused; extract private helpers for complex branches.724. Replace magic numbers with named constants including units (`RetryDelayMilliseconds`).7374## Types And Data Modeling75761. Enable nullable reference types and treat warnings as actionable.772. Prefer explicit DTO/value objects over `dynamic` or loosely typed dictionaries.783. Use `record` for immutable data where semantics fit.794. Define explicit boundary contracts for request/response models.8081## Error Handling And Async Behavior82831. Throw specific exception types with actionable context.842. Catch exceptions at boundaries and map intentionally (retry/log/translate/rethrow).853. Avoid blanket `catch (Exception)` unless rethrowing after required handling.864. Pass `CancellationToken` through async chains.875. Avoid sync-over-async (`.Result`, `.Wait()`).8889## Configuration And Environment90911. Bind configuration to typed options and validate at startup.922. Fail startup when required environment variables/config are missing.933. Do not add silent fallback defaults for required configuration.944. Keep secrets in secret stores, not source code.9596## Security And Compliance97981. Validate/sanitize external input.992. Use parameterized queries/ORM bindings; never concatenate SQL.1003. Enforce authn/authz close to entry points.1014. Avoid logging sensitive data (tokens, passwords, PII).102103## Performance And Resource Usage1041051. Profile before micro-optimization.1062. Use streaming/pagination for large datasets.1073. Reuse outbound clients (`IHttpClientFactory`).1084. Respect cancellation and timeout policies for outbound I/O.109110## Testing And Verification1111121. Add unit tests for business logic and integration tests for boundaries.1132. Cover nullability, cancellation, timeout, invalid payloads, and concurrency edges.1143. Add regression tests for each fixed defect.1154. Document manual verification when automation is infeasible.116117## Observability And Operations1181191. Use structured logs with correlation/request IDs.1202. Emit metrics for latency, errors, and dependency calls.1213. Map failures to stable operational signals (status/error codes).1224. Ensure telemetry supports incident triage.123124## CI Required Quality Gates (check-only)1251261. Run `dotnet format --verify-no-changes`.1272. Run `dotnet build -warnaserror`.1283. Run `dotnet test`.1294. Reject changes that hide failures with broad fallbacks.130131## Optional Autofix Commands (local)1321331. Run `dotnet format`.