csharp
Writes, reviews, refactors and debugs C# and .NET code (types, nullable references, async and cancellation, exceptions, DI, options and logging in the generic host, file-based apps). Use for work in *.cs or *.csx files, "review this C# class", CS86xx nullable warnings, CA or IDE warnings and .editorconfig severity, a deadlock or sync-over-async bug, or a rename across a solution. Not for Godot C# (godot-csharp).
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- csharp
- license
- MIT
- description
- Writes, reviews, refactors and debugs C# and .NET code (types, nullable references, async and cancellation, exceptions, DI, options and logging in the generic host, file-based apps). Use for work in *.cs or *.csx files, "review this C# class", CS86xx nullable warnings, CA or IDE warnings and .editorconfig severity, a deadlock or sync-over-async bug, or a rename across a solution. Not for Godot C# (godot-csharp).
02 资源文件 6
- 参考文档references/cli-apps.md3.7 KB
- 参考文档references/file-based-apps.md3.2 KB
- 参考文档references/net11-apis.md4.5 KB
- 参考文档references/nullable.md8.8 KB
- 参考文档references/refactoring.md5.3 KB
- 参考文档references/sdk-setup.md2.9 KB
03 SKILL.md 正文
C#
Keep the observable contract (public API, exceptions, nullability annotations, threading and cancellation behavior, serialized names) unless the request changes it.
Not for: MSBuild and build failures (msbuild), package versions (nuget), tests and dotnet test (dotnet-testing), TFM upgrades, SDK-style conversion and AOT readiness (dotnet-upgrade-guide), ASP.NET Core endpoints (aspnet-core), Blazor (blazor), EF Core (ef-core), hot-path tuning and benchmarks (dotnet-diagnostics), analyzers and source generators (roslyn-analyzers).
Orient
- Read
global.json,Directory.Build.props/.targets, the project file (TargetFramework(s),LangVersion,Nullable,ImplicitUsings,TreatWarningsAsErrors,AnalysisLevel), and.editorconfig. Rundotnet --versionfrom the repo root. - Use only language features the project's language version allows: the default follows the TFM (net8.0 is C# 12, net9.0 C# 13, net10.0 C# 14, net11.0 C# 15). Don't raise
LangVersion, the TFM or the SDK unless asked. A multi-targeted project is limited by its oldest TFM;netstandard2.0and .NET Framework also lack newer BCL APIs. - Find definitions, callers and implementations with codebase-memory when the repo is indexed (
search_graph,trace_path,get_code_snippet), then the C# language server (csharp-ls) through the LSP tool, then Grep. Before changing a member, list its references; include everypartialdeclaration and edit generator inputs, never*.g.csoutput. - For a library API, check the docs for the referenced version (Context7
resolve-library-idthenquery-docs, or Microsoft Learn). - Use the repo's build and test commands when it documents them (README,
build.sh, CI). Reproduce with the narrowest one. - Read references/sdk-setup.md when the required SDK isn't installed or
global.jsondoesn't resolve.
Types and APIs
- Least exposure:
private, theninternal, thenpublic. Seal classes not designed for inheritance. Treat every public member as a compatibility promise. - Add an interface only for a real second implementation or an external dependency a test must replace. Don't wrap existing abstractions.
- Records for DTOs and value-like data;
readonly record structfor small values. Records give value equality, so don't put mutable collections or entities in them. requiredandinitfor objects that must be fully initialized; primary constructors for injected dependencies (their parameters are mutable captures, so assign toreadonlyfields when that matters).- Collection expressions (
[],[..a, ..b]) and pattern matching (is, switch expressions, list patterns) where the language version allows. ReturnIReadOnlyList<T>orIEnumerable<T>, notList<T>, from public APIs. - Follow the repo's naming and file layout; otherwise .NET conventions (PascalCase members,
_camelCaseprivate fields,Iprefix on interfaces,Asyncsuffix on async methods, file-scoped namespaces). - When fixing one method, check its siblings for the same defect. Comments explain why, not what.
Nullability
- With
<Nullable>enable</Nullable>, a?on a reference type is a promise about null; the compiler doesn't enforce it at runtime. KeepArgumentNullException.ThrowIfNull(x)(andArgumentException.ThrowIfNullOrWhiteSpacefor strings) on public entry points. - A method that can return null returns
T?. Neverreturn null!ordefault!behind a non-nullable signature. - Use
!only where the value is provably non-null and the compiler can't see it, with a comment. Prefer[NotNullWhen],[MemberNotNull]and similar attributes over!at every call site. - Don't fix CS8602 by switching
x.M()tox?.M(): that silently skips the call. Decide whether null is valid, then annotate or guard. - Deserialized DTOs can hold null whatever the declared type; validate at the boundary.
- Read references/nullable.md when enabling nullable in a project, fixing CS86xx warnings in bulk, or annotating a library's public API.
Async and cancellation
- Async all the way. Never block on async code (
.Result,.Wait(),.GetAwaiter().GetResult()) in request, UI or library code; that is the classic deadlock and thread-pool starvation source. Avoidasync voidexcept event handlers. - Accept a
CancellationToken(last parameter,cancellationToken = defaulton public APIs) and pass it to every call that takes one, includingTask.Delay. CheckThrowIfCancellationRequested()in long loops. LetOperationCanceledExceptionpropagate; don't log it as an error. - Timeouts:
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(timeout);and passcts.Token. If you useTask.WhenAnyfor a timeout, cancel the loser. ConfigureAwait(false)in library code; omit it in apps (ASP.NET Core has no sync context, UI apps need theirs).- Return the task directly instead of
async/awaitonly when there is nousing,tryor code after it. - Default to
Task/Task<T>. UseValueTaskonly where measured to help, and await it exactly once. await usingforIAsyncDisposable; implement it when the type owns async resources.- No fire-and-forget: queue background work to a hosted service or
Channel<T>so errors are observed and shutdown waits for it. - HTTP:
IHttpClientFactoryor a long-livedHttpClient, never one per call. For large responses useHttpCompletionOption.ResponseHeadersRead, then stream (ReadFromJsonAsync,JsonSerializer.DeserializeAsync). - Locks: never
awaitinsidelock; useSemaphoreSlim.WaitAsync. On .NET 9+,System.Threading.Lockfor synchronous locks. - Console apps: wire Ctrl+C to a
CancellationTokenSource, and exit with 130 on cancellation.
Errors
- Throw the most specific type (
ArgumentException,InvalidOperationException,KeyNotFoundException, or a domain exception); never throw or catch bareExceptionexcept at a top-level boundary that logs and maps it. - Never swallow: log with context and rethrow (
throw;, notthrow ex;), or let it propagate. Use exception filters (catch (HttpRequestException e) when (e.StatusCode == ...)). - Expected outcomes (validation failure, not found) can be return values (
TryX(out T), a result type) instead of exceptions, following the codebase's existing style.
Generic host: DI, options, logging
- Lifetimes: singleton must not depend on scoped (captive dependency). Resolve scoped services from a singleton or hosted service with
IServiceScopeFactory.CreateScope(). KeepValidateScopesandValidateOnBuildon in development. - Options: bind with
services.AddOptions<T>().Bind(config.GetSection(...)).ValidateDataAnnotations().ValidateOnStart(). InjectIOptions<T>(singleton, read once),IOptionsSnapshot<T>(scoped, recomputed per scope), orIOptionsMonitor<T>(singleton, change notifications) by need. - Logging: message templates with named placeholders (
logger.LogInformation("Order {OrderId} shipped", id)), never string interpolation. For hot paths use source-generated[LoggerMessage]partial methods. Never log secrets or personal data. - Time and randomness: inject
TimeProvider(.NET 8+) instead ofDateTime.Now/UtcNow, so tests can useFakeTimeProvider. - Config from environment and
appsettings.*.json; secrets from user-secrets in development and a secret store in production, never committed.
Verify
dotnet build -warnaserror(or the repo's build) on the changed projects, and for every TFM of a multi-targeted project (-f net8.0), since a green default target hides breaks on another.- The narrowest relevant tests (
dotnet-testinghas the filter syntax for VSTest versus Microsoft.Testing.Platform), then the wider suite when a shared or public surface changed. dotnet format --verify-no-changeswhen the repo enforces style. Fix analyzer findings (IDE/CA) the repo enables; suppress only with a justification attribute or.editorconfigentry, never wholesale.- Report the exact commands and results, including any TFM or test you could not run.
References
- references/refactoring.md when renaming, moving, extracting, inlining or consolidating code, especially public,
partial, multi-targeted or reflection-reached symbols. - references/nullable.md for nullable migration and annotation rules, including EF Core and ASP.NET Core effects.
- references/file-based-apps.md for
dotnet run app.cs,#:package/#:sdkdirectives, and quick C# experiments without a project. - references/cli-apps.md when building or changing a System.CommandLine (v2) CLI.
- references/sdk-setup.md for installing an SDK into the repo without touching the system, and
global.jsonpinning. - references/net11-apis.md when the project targets
net11.0: newProcessandSystem.Text.JsonAPIs (.NET 11 went GA on 2026-11-10).
04 同仓库更多 Skills
nuget
Manages NuGet dependencies and packages in .NET repos. Use for Directory.Packages.props and Central Package Management, bumping or aligning package versions, NU1xxx restore warnings, nuget.config sources and source mapping, vulnerable-package audits, lock files, dotnet pack metadata, publishing to nuget.org with trusted publishing, or authoring, validating and packing `dotnet new` templates (template.json, a template missing from `dotnet new list`).
msbuild
Diagnoses MSBuild failures and slow builds and reviews .NET build XML. Use for a failing dotnet build, restore, pack or publish, .csproj/.props/.targets conditions and custom targets, binlog capture and replay, "it rebuilds when nothing changed", slow evaluation or builds, bin/obj clashes, or Directory.Build.* layering.