lang-csharp
Use when the user asks about C# on .NET 10, async/await, LINQ, nullable reference types, Span<T>, records, pattern matching, IDisposable, xUnit or the dotnet…
от j4flmao★ 47 звёзд на GitHub
Установить lang-csharp в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
C#
Purpose
C# combines a managed runtime with value types, spans and a mature async model. Most production bugs come from async misuse (deadlocks, async void, unobserved tasks), null handling, and hidden allocations. This skill covers the idioms and settings that prevent them on current .NET.
Agent Protocol
Trigger
"C#", "csharp", ".NET", "dotnet", "async await", "LINQ", "nullable reference types", "Span", "records", "pattern matching", "IDisposable", "xUnit", "NuGet".
Input Context
- Target framework (
net10.0LTS,net8.0LTS,netstandard2.0for libraries) and C# language version - App type (library, console, ASP.NET Core, worker, desktop) and AOT/trimming needs
- Analyzer/nullable settings in the
.csproj
Output Artifact
C# code, .csproj settings, or review findings. No file unless requested.
Response Format
TFM/C#: {net10.0 / C# 14}
Change: {what and why}
Code: {snippet}
Async/nullability notes: {cancellation, ConfigureAwait, null contracts}
Verify: {dotnet test, analyzers, benchmarks}
1. Project Baseline
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>latest-recommended</AnalysisLevel>
</PropertyGroup>
- .NET releases yearly in November; even-numbered releases are LTS (3 years), odd ones STS (2 years as of .NET 9's policy change). Pin the SDK with
global.json; central package versions viaDirectory.Packages.props.
2. Types
class(reference),struct(value; keep small and preferablyreadonly struct),record/record structfor immutable data with value equality andwithexpressions.- Primary constructors (C# 12) for DI-style classes:
public sealed class OrderService(IClock clock, IOrderRepo repo) { ... }. - Pattern matching:
switchexpressions, property and list patterns:
decimal Discount(Order o) => o switch
{
{ Total: > 1000m, Customer.IsVip: true } => 0.15m,
{ Items: [_, _, _, ..] } => 0.05m, // 3+ items
_ => 0m,
};
- Nullable reference types:
string?may be null,stringmust not. Fix warnings rather than suppressing with!; validate at boundaries withArgumentNullException.ThrowIfNull(arg).
3. Async/Await
- Return
Task/Task<T>(orValueTaskfor hot paths that often complete synchronously — await it once only).async voidonly for event handlers: exceptions there crash the process. - Never block on async code (
.Result,.Wait(),GetAwaiter().GetResult()): it wastes thread-pool threads and deadlocks under a synchronisation context (UI, legacy ASP.NET). - Pass
CancellationTokenthrough every async API and honour it. - Libraries may use
ConfigureAwait(false); ASP.NET Core has no synchronisation context, so it is unnecessary in app code there. - Concurrency:
Task.WhenAllfor fan-out,Parallel.ForEachAsyncwithMaxDegreeOfParallelismfor bounded parallel I/O,Channel<T>for producer/consumer,SemaphoreSlimfor async locking (nolockaroundawait).
public async Task<IReadOnlyList<Price>> FetchAllAsync(IEnumerable<string> skus, CancellationToken ct)
{
var results = new ConcurrentBag<Price>();
await Parallel.ForEachAsync(skus, new ParallelOptions { MaxDegreeOfParallelism = 8, CancellationToken = ct },
async (sku, token) => results.Add(await _client.GetPriceAsync(sku, token)));
return results.ToList();
}
4. LINQ and Allocations
- LINQ is fine for clarity; in hot loops it allocates enumerators/delegates — use loops or
Span<T>there after profiling. - Deferred execution: queries run on enumeration; materialise once (
ToList()) when enumerating more than once. With EF Core, keep queriesIQueryableuntil the server-side shape is final. Span<T>/ReadOnlySpan<T>/Memory<T>for slicing without copies;stackallocfor small buffers;ArrayPool<T>.Sharedfor large temporary arrays;StringBuilderorstring.Createfor building strings in loops.- Measure with BenchmarkDotNet (
[MemoryDiagnoser]), not stopwatch loops.
5. Resources and Exceptions
using var x = ...;/await usingforIDisposable/IAsyncDisposable. Do not dispose objects you do not own.HttpClient: reuse viaIHttpClientFactoryor a long-lived static instance (withPooledConnectionLifetime) —new HttpClient()per request exhausts sockets.- Throw specific exceptions; catch where you can handle; rethrow with
throw;to keep the stack trace. Log with structured templates:logger.LogError(ex, "Failed to load order {OrderId}", id);.
6. Performance and Deployment
- Server GC + tiered compilation + Dynamic PGO are defaults on modern .NET.
- Native AOT (
<PublishAot>true</PublishAot>) for fast-starting CLIs/services: requires trim-safe code — prefer source generators (System.Text.JsonJsonSerializerContext, reg
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/csharp-advanced.md
- references/csharp-fundamentals.md
- references/csharp-testing.md
- references/design-patterns-generics.md
FAQ
Что делает скилл lang-csharp?
Use when the user asks about C# on .NET 10, async/await, LINQ, nullable reference types, Span<T>, records, pattern matching, IDisposable, xUnit or the dotnet CLI. Produces idiomatic, allocation-aware C# and project setup. Not for ASP.NET Core architecture (use dotnet-architecture), Unity scripting (use unity) or MAUI apps (use mobile-dotnet-maui).
Как установить скилл lang-csharp?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл lang-csharp запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…