Agent skill

Csharp Rules

by softspark in softspark/ai-toolkit

C/.NET coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

Apache-2.0Auto-check passedTesting & QA

Install Csharp Rules

skills CLI
$ npx skills add softspark/ai-toolkit --skill csharp-rules -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install softspark/ai-toolkit csharp-rules --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/softspark/ai-toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/app/skills/csharp-rules .claude/skills/csharp-rules && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
csharp-rules
GitHub stars
179
Token cost
~3.5k tokens
SKILL.md length
1,566 words
Files
1
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

C/.NET coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

  • Tasks that involve Unit testing
  • SKILL.md covers Naming, Nullable Reference Types, Records and Types and Pattern Matching, plus 21 more sections
  • Calls dotnet

What it does

Csharp Rules is an agent skill from softspark/ai-toolkit. C/.NET coding rules: style, patterns, security, testing. Triggers: .cs, .csproj, .sln, ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, dotnet.

Its SKILL.md is about 3.5k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Testing & QA, covering Unit testing. It works with C#, ASP.NET Core and .NET. The repository describes itself as: Professional-grade AI coding toolkit: 94 skills, 44 agents, multi-platform (Claude, Cursor, Windsurf, Copilot, Gemini, Cline, Roo Code, Aider, Augment, Antigravity, Codex CLI… The licence is Apache-2.0.

When your agent uses it

  • Tasks that involve Unit testing

Example prompts

  • “/csharp-rules”

Requirements

  • Pre-approved tools (allowed-tools): Read

What it can do on your machine

Read from SKILL.md and the folder at commit d64db2b. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • dotnet

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Csharp Rules loads about 3.5k tokens when it runs. Until then it costs about 40 tokens; SKILL.md has 1,566 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~40
When it runs · the whole SKILL.md, loaded when a task matches
~3.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from softspark/ai-toolkit at commit d64db2b, republished under its Apache-2.0 licence (© softspark). 1,566 words, ~3,474 tokens.

Download SKILL.mdSave it as .claude/skills/csharp-rules/SKILL.md (or your agent's skills folder).
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.
allowed-tools
Read
effort
medium
user-invocable
false

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.
Show full SKILL.md (648 more words)Show less

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.

© softspark, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in app/skills/csharp-rules of softspark/ai-toolkit.

Open the folder on GitHubat commit d64db2b

Compare with similar skills

Csharp Rules next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Csharp Rules compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Csharp Rules this skillsoftspark/ai-toolkit179—~3.5kAutomated safety check: PassApache-2.0
Using Dotnetnovotnyllc/dotnet-artisan233—~2.3kAutomated safety check: WarnMIT
Csharp ConventionsGoldziher/ai-rulez153—~363Automated safety check: PassMIT
ScottPlot Test RunnerScottPlot/ScottPlot6.8k—~308Automated safety check: PassMIT
Aspire Integration TestingDevBetterCom/DevBetterWeb1572 repos~2.3kAutomated safety check: PassNone
Akka.NET Testing PatternsAaronontheweb/dotnet-skills1.2k1 repos~2.4kAutomated safety check: PassMIT

Similar skills

  • Using Dotnet

    novotnyllc/dotnet-artisan

    Detects .NET intent for any C, ASP.NET Core, EF Core, Blazor, MAUI, Uno Platform, WPF, WinUI, SignalR, gRPC, xUnit, NuGet, or MSBuild request from prompt keywords and repository signals (.sln…

    233 GitHub stars~2.3k tokensUpdated 1 mo ago
    Backend & APIsAuto-check: warnings
  • Csharp Conventions

    Goldziher/ai-rulez

    C code conventions covering .NET 8+/C 12, nullable reference types, Roslyn analyzers, xUnit, record types, async/await discipline, and dependency security.

    153 GitHub stars~363 tokensUpdated today
    Testing & QAAuto-check passed
  • ScottPlot Test Runner

    ScottPlot/ScottPlot

    Run or add ScottPlot 5 tests. Use for unit-test and cookbook-test work; unless explicitly asked otherwise, restrict manual test execution to the Unit Tests…

    6.8k GitHub stars~308 tokensUpdated 1 mo ago
    Testing & QAAuto-check passed
  • Aspire Integration Testing

    DevBetterCom/DevBetterWeb

    Write integration tests using .NET Aspire's testing facilities with xUnit.

    157 GitHub starsUsed in 2 repos~2.3k tokens
    Testing & QAAuto-check passed
  • Akka.NET Testing Patterns

    Aaronontheweb/dotnet-skills

    Shows how to test Akka.NET actors with Akka.Hosting.TestKit: swapping services for fakes, using TestProbes, and checking persistence, plus when the older TestKit still fits.

    1.2k GitHub starsUsed in 1 repo~2.4k tokens
    Testing & QAAuto-check passed
  • Verify

    valdisiljuconoks/LocalizationProvider

    Build the solution and run unit tests to verify changes are correct.

    180 GitHub stars~159 tokensUpdated 3 mo ago
    Testing & QAAuto-check passed

More from softspark/ai-toolkit

All 112 skills in this repo
  • Prepare Test Env

    softspark/ai-toolkit

    Prepare or verify a project QA environment with source identity, readiness, browser access, evidence paths and owned cleanup.

    179 GitHub stars~1.8k tokensUpdated today
    Auto-check: notes
  • A11y Validate

    softspark/ai-toolkit

    Accessibility validator: WCAG 2.1 AA, EN 301 549, EAA. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.8k tokensUpdated today
    Auto-check: notes
  • Analyze

    softspark/ai-toolkit

    Analyzes code quality, complexity, patterns across codebase.

    179 GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Autonomous Dev

    softspark/ai-toolkit

    Drives a brief, specification, issue or existing PR through implementation, review, tests and QA to a ready PR.

    179 GitHub stars~2.6k tokensUpdated today
    Auto-check: notes
  • Brand Voice

    softspark/ai-toolkit

    Direct technical voice for docs, README, user-facing text. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~2.1k tokensUpdated today
    Auto-check passed
  • CI

    softspark/ai-toolkit

    Detect/generate/debug CI pipeline config (GitHub Actions, GitLab CI).

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check: notes

Questions about Csharp Rules

What does Csharp Rules do?

C/.NET coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit. Csharp Rules is an agent skill from softspark/ai-toolkit.NET coding rules: style, patterns, security, testing.

When should I use Csharp Rules?

Csharp Rules fits situations like: tasks that involve Unit testing.

How do I install Csharp Rules in Claude Code?

Run `npx skills add softspark/ai-toolkit --skill csharp-rules -a claude-code`. Or copy the skill folder (app/skills/csharp-rules in softspark/ai-toolkit) into .claude/skills/csharp-rules in your project. Claude Code loads it when a task matches its description.

How do I install Csharp Rules in Codex?

Run `npx skills add softspark/ai-toolkit --skill csharp-rules -a codex`. Or copy the skill folder (app/skills/csharp-rules in softspark/ai-toolkit) into .agents/skills/csharp-rules in your project. Codex loads it when a task matches its description.

Can I use Csharp Rules in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add softspark/ai-toolkit --skill csharp-rules -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/csharp-rules, .gemini/skills/csharp-rules, .github/skills/csharp-rules and .opencode/skills/csharp-rules in your project.

What does Csharp Rules need to run?

Going by SKILL.md and its folder, Csharp Rules needs the command-line tools its instructions call (dotnet). Its frontmatter pre-approves these tools: Read.

Does Csharp Rules access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Csharp Rules safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Csharp Rules use?

Csharp Rules is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Csharp Rules use?

About 3.5k tokens (SKILL.md is roughly 14k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Csharp Rules?

Skills that share tags, products or a category with Csharp Rules: Using Dotnet (novotnyllc/dotnet-artisan, 233 stars), Csharp Conventions (Goldziher/ai-rulez, 153 stars), ScottPlot Test Runner (ScottPlot/ScottPlot, 6.8k stars) and Aspire Integration Testing (DevBetterCom/DevBetterWeb, 157 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Csharp Rules?

softspark (a GitHub user) maintains it in softspark/ai-toolkit, which has 179 GitHub stars. The repository holds 112 skills in this directory. The repository was last updated on October 7, 2026.

Source: softspark/ai-toolkit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.