csharp-style-guide
SKILL.md
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.mdas 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.mdfor 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
dynamicor loosely typed dictionaries. - Use
recordfor 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
CancellationTokenthrough 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.
Weekly Installs
4
Repository
kentoshimizu/sw…t-skillsGitHub Stars
4
First Seen
Feb 28, 2026
Security Audits
Installed on
opencode4
gemini-cli4
codebuddy4
github-copilot4
codex4
kimi-cli4