csharp-rules

C#/.NET rules: coding guidelines for C#/.NET covering style, design patterns, security, and testing. Trigger conditions include .cs, .csproj, .sln files or ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, and dotnet-related projects.

Last repository push
GitHub Stars
180
Forks
21
Issues / PRs
0

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "csharp-rules" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-c1194d353f1fb531993c0ad77383619c8955c0e7fca37ee8433b0843135f3cdc. Verify the upstream source and version against https://github.com/softspark/ai-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

C#/.NET rules: coding guidelines for C#/.NET covering style, design patterns, security, and testing. Trigger conditions include .cs, .csproj, .sln files or ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, and dotnet-related projects.

0 Downloads

Introduction source: third_party · softspark · 0.0.1 Reference

SkillPi interpretation

Tasks
C#/.NET coding rules: style, patterns, security, testing. Triggers: .cs, .csproj, .sln, ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, dotnet.
Inputs and outputs
Use data annotations (`[Required]`, `[StringLength]`, `[Range]`) on request models. Use `[ApiController]` for automatic 400 responses on validation failure. Use FluentValidation for complex, rule-based validation logic. Never trust client-provided IDs. Verify resource ownership server-side. Sanitize HTML input with a library like HtmlSanitizer. Never render raw user HTML.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: csharp-rules
description: "C#/.NET coding rules: style, patterns, security, testing. Triggers: .cs, .csproj, .sln, ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, dotnet."
effort: medium
user-invocable: false
allowed-tools: Read

C#/.NET Rules

These rules come from app/rules/csharp/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in C#/.NET. Apply them when writing or reviewing C#/.NET code.

C# Coding Style

Naming

  • PascalCase: classes, structs, enums, interfaces, methods, properties, events.
  • camelCase: local variables, parameters, private fields.
  • Prefix interfaces with I: IUserRepository, IDisposable.
  • Prefix private fields with _: private readonly ILogger _logger;.
  • UPPER_SNAKE: not conventional in C#. Use PascalCase for constants.

Nullable Reference Types

  • Enable <Nullable>enable</Nullable> in all projects.
  • Use string? only when null is semantically meaningful.
  • Use ! (null-forgiving) operator sparingly -- only when compiler cannot infer.
  • Use ?? (null-coalescing) and ?. (null-conditional) for safe navigation.
  • Use required modifier (C# 11) on properties that must be set at initialization.

Records and Types

  • Use record for immutable value objects and DTOs.
  • Use record struct for small, stack-allocated value types.
  • Use init properties for immutable-after-construction objects.
  • Use with expressions for non-destructive mutation of records.
  • Use primary constructors (C# 12) for concise class definitions.

Pattern Matching

  • Use is pattern for type checks: if (obj is string s).
  • Use switch expressions for exhaustive matching over enums/types.
  • Use property patterns: user is { Age: > 18, Role: "admin" }.
  • Use relational patterns: size is > 0 and < 100.
  • Use list patterns (C# 11): numbers is [1, 2, .., var last].

Async/Await

  • Suffix async methods with Async: GetUserAsync().
  • Return Task<T> or ValueTask<T>, never void (except event handlers).
  • Use await with ConfigureAwait(false) in library code.
  • Use CancellationToken parameters in all async public APIs.
  • Prefer ValueTask<T> when synchronous completion is common.

File Organization

  • One type per file. File name matches type name.
  • Use file-scoped namespaces (C# 10): namespace MyApp.Services;.
  • Order members: fields, constructors, properties, public methods, private methods.
  • Use global using directives in a single GlobalUsings.cs file.

Formatting

  • Use .editorconfig with C# style rules committed to the repository.
  • Use dotnet format for automated formatting.
  • Use Roslyn analyzers for compile-time style enforcement.
  • Max line length: 120 characters.

C# Frameworks

ASP.NET Core

  • Use minimal APIs for simple endpoints. Use controllers for complex APIs.
  • Use [ApiController] attribute for automatic model validation and error responses.
  • Use Results.Ok(), Results.NotFound() for typed HTTP results.
  • Use endpoint filters / middleware for cross-cutting concerns.
  • Use IHostedService / BackgroundService for long-running background tasks.
  • Map routes with app.MapGet(), app.MapPost() for minimal API style.

Entity Framework Core

  • Use code-first migrations: dotnet ef migrations add, dotnet ef database update.
  • Use DbContext with scoped lifetime (one per request).
  • Use AsNoTracking() for read-only queries. Use AsTracking() only for updates.
  • Use Include() / ThenInclude() for eager loading related entities.
  • Use shadow properties for audit fields (CreatedAt, UpdatedAt).
  • Use HasQueryFilter() for soft-delete and multi-tenancy global filters.

Blazor

  • Use Blazor Server for internal tools. Use Blazor WASM for public-facing SPAs.
  • Use @inject for dependency injection in components.
  • Use EventCallback<T> for parent-child component communication.
  • Use CascadingValue for deeply shared state (theme, auth).
  • Use StateContainer pattern with events for cross-component state management.

SignalR

  • Use strongly-typed hubs: Hub<IClientMethods> for compile-time safety.
  • Use HubContext<T> for sending messages from outside hubs.
  • Use groups for targeted broadcasting: Groups.AddToGroupAsync().
  • Configure automatic reconnection on the client side.

MassTransit / Messaging

  • Use MassTransit for message bus abstraction over RabbitMQ/Azure Service Bus.
  • Define messages as record types for immutability.
  • Use consumers (IConsumer<T>) for message handling.
  • Use sagas for long-running, multi-step workflows with state.
  • Use retry and circuit breaker policies for transient failures.

Logging

  • Use ILogger<T> via DI. Never instantiate loggers manually.
  • Use structured logging: _logger.LogInformation("User {UserId} logged in", userId).
  • Use Serilog with sinks for structured, centralized logging.
  • Use log scopes for request correlation: using (_logger.BeginScope(...)).

Configuration

  • Use appsettings.json + environment-specific overrides + environment variables.
  • Bind configuration sections to strongly-typed classes with IOptions<T>.
  • Use IOptionsMonitor<T> for configuration that changes at runtime.
  • Validate configuration at startup with ValidateDataAnnotations().

Health Checks

  • Use app.MapHealthChecks("/health") for liveness probes.
  • Register custom health checks for database, cache, and external service dependencies.
  • Use AspNetCore.HealthChecks.* NuGet packages for common checks.

C# Patterns

Error Handling

  • Use exceptions for truly exceptional conditions. Use Result<T> pattern for expected failures.
  • Create domain exception hierarchies: class DomainException : Exception.
  • Use when clause in catch: catch (HttpRequestException e) when (e.StatusCode == 404).
  • Use ExceptionDispatchInfo.Capture(e).Throw() to preserve original stack trace.
  • Return Result<T, Error> types for operations with expected failure modes.

Async Patterns

  • Use Task.WhenAll() for concurrent independent operations.
  • Use SemaphoreSlim for async-compatible resource limiting.
  • Use Channel<T> for async producer-consumer patterns.
  • Use IAsyncEnumerable<T> for streaming data from async sources.
  • Use Polly for retry, circuit breaker, and timeout policies.
  • Never use .Result or .Wait() on tasks (deadlock risk). Always await.

Dependency Injection

  • Use constructor injection exclusively. Avoid service locator pattern.
  • Register services in Program.cs or IServiceCollection extension methods.
  • Use Scoped for request-lifetime services, Singleton for stateless, Transient for lightweight.
  • Use IOptions<T> pattern for configuration injection.
  • Validate DI registrations at startup with ValidateOnBuild = true.

LINQ

  • Use method syntax for complex queries. Use query syntax for joins.
  • Use FirstOrDefault() over First() for safe access.
  • Use AsNoTracking() for read-only EF Core queries (performance).
  • Avoid materializing large collections: use IQueryable<T> until final projection.
  • Use Select() to project only needed columns from database queries.

Disposable Pattern

  • Implement IAsyncDisposable for async cleanup.
  • Use await using var resource = ...; for deterministic async disposal.
  • Use IDisposable with using declaration (C# 8) for scope-based cleanup.
  • Register disposable services in DI container (auto-disposed at scope end).

Mediator / CQRS

  • Use MediatR for command/query separation and pipeline behaviors.
  • Commands: IRequest<Result> for mutations. Queries: IRequest<T> for reads.
  • Use pipeline behaviors for cross-cutting: validation, logging, transactions.
  • Keep handlers thin: delegate to domain services for business logic.

Value Objects

  • Use record types for value objects with structural equality.
  • Use factory methods with validation: public static Result<Email> Create(string value).
  • Override ToString() for logging-friendly representations.
  • Use implicit/explicit operators sparingly for primitive wrapper conversions.

Anti-Patterns

  • Service locator: inject dependencies, do not resolve from container.
  • async void: use only for event handlers. Everything else returns Task.
  • Nested try-catch: flatten with early returns or guard clauses.
  • Anemic domain model: put behavior in domain objects, not only services.
  • Over-abstracting: do not create interfaces for classes with only one implementation.

C# Security

Input Validation

  • Use data annotations ([Required], [StringLength], [Range]) on request models.
  • Use [ApiController] for automatic 400 responses on validation failure.
  • Use FluentValidation for complex, rule-based validation logic.
  • Never trust client-provided IDs. Verify resource ownership server-side.
  • Sanitize HTML input with a library like HtmlSanitizer. Never render raw user HTML.

SQL Injection

  • Use EF Core parameterized queries exclusively. Never concatenate SQL.
  • Use FromSqlInterpolated() over FromSqlRaw() for raw SQL (auto-parameterized).
  • Use stored procedures via context.Database.ExecuteSqlInterpolatedAsync().
  • Audit all FromSqlRaw() calls for parameter interpolation risks.
  • Use Dapper with parameterized queries: @param syntax in SQL strings.

Authentication

  • Use ASP.NET Core Identity for user management and password hashing.
  • Use AddAuthentication().AddJwtBearer() for JWT-based API auth.
  • Use short-lived access tokens (15 min) with refresh token rotation.
  • Use [Authorize] attribute globally. Use [AllowAnonymous] selectively.
  • Use HTTPS redirection: app.UseHttpsRedirection().

Authorization

  • Use policy-based authorization: [Authorize(Policy = "AdminOnly")].
  • Use IAuthorizationHandler for custom authorization logic.
  • Use resource-based authorization for object-level access control.
  • Default deny: apply [Authorize] at controller/app level, opt out per endpoint.
  • Check ownership in service layer, not just role membership.

CSRF and XSS

  • Use anti-forgery tokens for form-based submissions.
  • Razor/Blazor auto-encodes output. Never use @Html.Raw() with user data.
  • Set Content-Security-Policy headers to restrict script sources.
  • Use SameSite=Strict on cookies for CSRF mitigation.
  • Enable CORS only for specific origins. Never use AllowAnyOrigin() with credentials.

Data Protection

  • Use IDataProtectionProvider for symmetric encryption of sensitive data.
  • Use SecureString or ProtectedData for in-memory sensitive data (limited use).
  • Use ASP.NET Core Data Protection API for token and cookie encryption.
  • Hash passwords with PasswordHasher<T> (PBKDF2 with salt).

Secrets Management

  • Use dotnet user-secrets for local development. Use Azure Key Vault for production.
  • Use IConfiguration with environment variable providers. Never hardcode secrets.
  • Use [SensitiveData] attributes to exclude fields from logging and serialization.
  • Never log request headers containing Authorization or cookie values.

Dependency Security

  • Run dotnet list package --vulnerable to check for known CVEs.
  • Use Dependabot or NuGetAudit for automated vulnerability scanning.
  • Pin package versions explicitly. Avoid floating version ranges.
  • Update Microsoft.AspNetCore.* packages promptly for security patches.

C# Testing

Framework

  • Use xUnit as the primary test framework (modern, extensible).
  • Use NSubstitute for mocking (clean syntax, no setup boilerplate).
  • Use FluentAssertions for readable, expressive assertions.
  • Use Testcontainers for integration tests with databases and services.

File Naming

  • Test files: FooTests.cs in a separate *.Tests project.
  • Mirror source project namespace structure in test project.
  • Integration tests: separate *.IntegrationTests project.
  • Use [Collection("Database")] for shared fixtures across test classes.

Structure

  • Use [Fact] for single test cases. Use [Theory] for parameterized tests.
  • Use [InlineData] or [MemberData] for test data in theories.
  • Use constructor injection for per-test setup. Use IClassFixture<T> for shared setup.
  • Name tests: MethodName_Scenario_ExpectedResult.

Assertions (FluentAssertions)

  • Use result.Should().Be(expected) for value assertions.
  • Use action.Should().Throw<InvalidOperationException>() for exception testing.
  • Use collection.Should().ContainSingle(x => x.Id == 1) for collection assertions.
  • Use result.Should().BeEquivalentTo(expected) for deep object comparison.
  • Use execution.Should().CompleteWithinAsync(5.Seconds()) for timeout assertions.

Mocking (NSubstitute)

  • Create mocks: var repo = Substitute.For<IUserRepository>().
  • Stub returns: repo.GetAsync(1).Returns(user).
  • Verify calls: repo.Received(1).SaveAsync(Arg.Any<User>()).
  • Use Arg.Is<T>(predicate) for argument matching.
  • Use ReturnsForAnyArgs() for lenient stubs in arrangement-focused tests.

Integration Testing

  • Use WebApplicationFactory<Program> for ASP.NET Core integration tests.
  • Override services with WithWebHostBuilder(b => b.ConfigureServices(...)).
  • Use HttpClient from factory for endpoint testing.
  • Use Respawn for database cleanup between tests.
  • Use [Collection] attribute to prevent parallel execution of shared-resource tests.

Test Data

  • Use Builder pattern for complex test data: new UserBuilder().WithName("Ada").Build().
  • Use AutoFixture for auto-generated test data.
  • Use Bogus library for realistic fake data generation.
  • Keep test data creation close to the test, not in distant shared files.

Best Practices

  • Test behavior, not implementation. Avoid testing private methods.
  • Keep tests independent. No shared mutable state between tests.
  • Use CancellationToken.None explicitly in async test calls.
  • Run tests in CI with dotnet test --blame-hang-timeout 60s.

Version history

  1. v6.2.0 GitHub ↗
    Original release notes

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    Original release notes

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    Original release notes

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    Original release notes

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    Original release notes

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

Only the five most recent versions are shown. View full version history at the source ↗

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value95/100

Highlights

  • C#/.NET 编码规范覆盖全面,包含风格、框架、模式、安全、测试五大核心领域
  • 提供具体可落地的最佳实践,如 nullable 引用类型、async/await 规范、EF Core 优化等
  • 适用于日常开发、代码审查、团队标准化等多种高频刚需场景
Trigger Precision90/100

Highlights

  • 触发词覆盖完整,包含 .cs、.csproj、.sln、ASP.NET Core、EF Core、xUnit 等主流技术关键词
  • 边界清晰,不易与其他语言或框架的 Skill 产生误触
Structure and Standards85/100

Areas to improve

  • 缺少 When to Use 和端到端示例章节 Reported severity: Minor

    文档结构良好但缺少显式的使用场景说明和完整示例

    Recommendation: 建议补充 When to Use 章节说明适用场景,并增加一个端到端的代码示例展示规范应用

Highlights

  • 文档结构清晰,分 Style/Frameworks/Patterns/Security/Testing 五大模块组织
  • 每个子项都有具体规则说明,内容详实且层次分明
Execution Reliability95/100

Highlights

  • 内容来自 ai-toolkit 官方规则集,来源可信度高
  • 覆盖主要异常处理、安全实践和测试规范,无执行风险
  • 提供了具体的工具链建议(如 dotnet format、Roslyn analyzers)
Evidence Verifiability (mean of the first four)91/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Accounts, secrets or authorization

    Use a dedicated least-privilege account. Keep secrets out of public content and command logs; verify the receiving service and tenant.

    Mentioned in main document · lines 211

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.