[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74EEM7Z6AM6RQY04588KXC6":3,"skill-same:01M74EEM7Z6AM6RQY04588KXC6":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M74EEM7Z6AM6RQY04588KXC6","csharp-coding",null,"Apply when writing or editing C# (.cs) files. Behavioral corrections for error handling, resource management, async patterns, data modeling, type safety, nullability, security defaults, and common antipatterns. Project conventions always override these defaults.","tamarillo-ai\u002Ftheta","tamarillo-ai","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F264659913?v=4","01M732W8TW61PS979NJ2W4Z6XZ","tamarillo.ai","01M732W8VRBBGT4F0Q3B2HNGTQ",15,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcodex-cli\u002Fregression\u002Fjust-works\u002F.codex\u002Fskills\u002Fcsharp-coding\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: csharp-coding\ndescription: Apply when writing or editing C# (.cs) files. Behavioral corrections for error handling, resource management, async patterns, data modeling, type safety, nullability, security defaults, and common antipatterns. Project conventions always override these defaults.\n---\n\n# C# Coding\n\nMatch the project's existing conventions. When uncertain, read 2-3 existing files to infer the local style. Check `.csproj` for `TargetFramework` (`net10.0` LTS or `net9.0` STS in 2026), C# `LangVersion` (default `latest`; assume C# 14 on .NET 10), nullable settings, and analyzer config. These defaults apply only when the project has no established convention.\n\n## Never rules\n\nThese are unconditional. They prevent bugs and vulnerabilities regardless of project style.\n\n- **Never `catch { }` or `catch (Exception) { }` without rethrow or logging.** Broad catches silently swallow bugs — a NullReferenceException from a typo looks the same as a transient network failure. Catch specific exception types. If you must catch broadly at a boundary, always log and rethrow or convert to a meaningful error.\n- **Never `throw ex`** — use `throw` or `throw new XException(\"msg\", ex)`. `throw ex` resets the stack trace, destroying the origin of the error. You'll spend hours debugging something the original stack trace would have shown instantly.\n- **Never `DateTime.Now`** — use `DateTime.UtcNow` or `DateTimeOffset.UtcNow`. `DateTime.Now` produces local time that varies by server timezone and breaks across DST transitions. `DateTimeOffset` is preferred when the timezone context matters.\n- **Never `async void`** — except for event handlers. `async void` methods cannot be awaited, their exceptions crash the process unobserved, and they break structured error handling. Use `async Task` instead.\n- **Never `.Result`, `.Wait()`, or `.GetAwaiter().GetResult()` on tasks** — these block the calling thread and cause deadlocks in ASP.NET Core and UI contexts. Use `await` instead. If you're in a sync context that genuinely cannot be made async, use `Task.Run(() => AsyncMethod()).GetAwaiter().GetResult()` as a last resort with a comment explaining why.\n- **Never `Random` for security** — `Random` is not cryptographically secure and is predictable. Use `RandomNumberGenerator.GetBytes()`, `RandomNumberGenerator.GetInt32()`, or `Convert.ToHexString(RandomNumberGenerator.GetBytes(n))` for tokens, keys, session IDs.\n- **Never string interpolation or concatenation in SQL** — use parameterized queries only. `$\"SELECT * FROM users WHERE id = {uid}\"` is always a SQL injection vulnerability. Use `@param` placeholders with `SqlCommand.Parameters` or your ORM's parameterization.\n- **Never `GC.Collect()`** — the GC is self-tuning. Forcing collection hurts performance in nearly all cases by promoting short-lived objects to higher generations. If you think you need it, you have a design problem to fix instead.\n- **Never mutable static fields** — statics are shared across all threads. Mutable statics cause race conditions that are extremely hard to reproduce and debug. Use `IOptions\u003CT>`, dependency injection, or `ConcurrentDictionary` if shared state is genuinely needed.\n- **Never `+` string concatenation in loops** — use `StringBuilder`. Strings are immutable in C#, so each `+` allocates a new string and copies all previous content — O(n^2) at scale. At 10k iterations this turns milliseconds into seconds.\n- **Never `dynamic` for typed data** — `dynamic` bypasses compile-time type checking, turns type errors into runtime exceptions, and kills IntelliSense. Use generics, interfaces, or pattern matching instead. Reserve `dynamic` for COM interop or truly dynamic scenarios.\n- **Never `Thread.Sleep()` in async code** — use `await Task.Delay()`. `Thread.Sleep` blocks the thread pool thread, starving other async operations. In ASP.NET Core this can exhaust the thread pool under load.\n\n## Error handling\n\nUse `throw` (not `throw ex`) when re-throwing to preserve the original stack trace. Wrap with inner exception when converting exception types at boundaries:\n\n```csharp\ntry\n{\n    var result = await httpClient.GetAsync(url, cancellationToken);\n    result.EnsureSuccessStatusCode();\n}\ncatch (HttpRequestException ex)\n{\n    throw new ServiceUnavailableException($\"Failed to reach {url}\", ex);\n}\n```\n\nUse exception filters (`when`) to catch conditionally without unwinding the stack:\n\n```csharp\ncatch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)\n{\n    return null;\n}\ncatch (HttpRequestException ex) when (ex.StatusCode >= HttpStatusCode.InternalServerError)\n{\n    logger.LogWarning(ex, \"Transient server error from {Url}\", url);\n    throw;\n}\n```\n\nCreate custom exception types when callers need to distinguish failure modes:\n\n```csharp\npublic class AppException : Exception\n{\n    public AppException(string message) : base(message) { }\n    public AppException(string message, Exception inner) : base(message, inner) { }\n}\n\npublic class NotFoundException : AppException\n{\n    public string Resource { get; }\n    public object Id { get; }\n\n    public NotFoundException(string resource, object id)\n        : base($\"{resource} not found: {id}\")\n    {\n        Resource = resource;\n        Id = id;\n    }\n}\n```\n\n## Resource cleanup\n\nUse `using` declarations for anything that implements `IDisposable` or `IAsyncDisposable`. Never instantiate `HttpClient`, database connections, streams, or similar without `using` or explicit `finally` cleanup.\n\n```csharp\n\u002F\u002F C# 8+ using declaration — disposed at end of scope\nusing var stream = File.OpenRead(path);\nusing var reader = new StreamReader(stream);\nvar content = await reader.ReadToEndAsync(cancellationToken);\n```\n\nFor async disposables:\n\n```csharp\nawait using var connection = new SqlConnection(connectionString);\nawait connection.OpenAsync(cancellationToken);\n```\n\nFor multiple resources or complex lifecycles, use explicit `try\u002Ffinally`:\n\n```csharp\nvar connection = new SqlConnection(connectionString);\ntry\n{\n    await connection.OpenAsync(cancellationToken);\n    \u002F\u002F work\n}\nfinally\n{\n    await connection.DisposeAsync();\n}\n```\n\nWhen implementing `IDisposable`, follow the pattern only if you hold unmanaged resources or own other disposables. Don't implement `IDisposable` on classes that don't own anything disposable — it adds ceremony for no benefit.\n\n## Async patterns\n\n**Always pass `CancellationToken` through the call chain.** Accept it as the last parameter and forward it to every async API. Omitting it means your code cannot be cancelled, leading to wasted resources and hung requests.\n\n```csharp\npublic async Task\u003CUser> GetUserAsync(int id, CancellationToken cancellationToken = default)\n{\n    var response = await _httpClient.GetAsync($\"\u002Fusers\u002F{id}\", cancellationToken);\n    response.EnsureSuccessStatusCode();\n    return await response.Content.ReadFromJsonAsync\u003CUser>(cancellationToken: cancellationToken)\n        ?? throw new NotFoundException(\"User\", id);\n}\n```\n\n**Prefer `Task` over `ValueTask`** unless profiling shows allocation pressure from a hot path that frequently completes synchronously. `ValueTask` has restrictions (can only be awaited once, no concurrent awaits) that make it error-prone as a default choice.\n\n**Use `ConfigureAwait(false)` in library code** (NuGet packages, shared class libraries) to avoid deadlocks in non-ASP.NET Core consumers. In ASP.NET Core application code, it's unnecessary — the default `SynchronizationContext` is null.\n\n**Use `Task.WhenAll` for independent concurrent work:**\n\n```csharp\nvar usersTask = GetUsersAsync(cancellationToken);\nvar ordersTask = GetOrdersAsync(cancellationToken);\n\nawait Task.WhenAll(usersTask, ordersTask);\n\nvar users = await usersTask;\nvar orders = await ordersTask;\n```\n\n**Never use `async` on a method that just returns another task.** Remove the state machine overhead:\n\n```csharp\n\u002F\u002F Wrong — unnecessary async state machine\npublic async Task\u003CUser> GetUserAsync(int id, CancellationToken ct)\n    => await _repository.GetByIdAsync(id, ct);\n\n\u002F\u002F Correct — direct passthrough\npublic Task\u003CUser> GetUserAsync(int id, CancellationToken ct)\n    => _repository.GetByIdAsync(id, ct);\n```\n\nException: keep `async`\u002F`await` when you need `using`, `try\u002Fcatch`, or when the method does work before\u002Fafter the awaited call.\n\n## C# 13 params collections\n\n`params` is no longer limited to arrays. Use `params ReadOnlySpan\u003CT>` for zero-allocation variadic APIs; use `params IEnumerable\u003CT>` when the caller may pass a lazy source:\n\n```csharp\npublic static int Sum(params ReadOnlySpan\u003Cint> values)\n{\n    var total = 0;\n    foreach (var v in values) total += v;\n    return total;\n}\n\nSum(1, 2, 3); \u002F\u002F no heap allocation\n```\n\nFor shared-state synchronization, prefer `System.Threading.Lock` over `lock (someObject)` where available:\n\n```csharp\nprivate readonly Lock _gate = new();\n\nvoid AppendSafely(string item)\n{\n    using (_gate.EnterScope()) { _items.Add(item); }\n}\n```\n\n## Nullability\n\nEnable nullable reference types (`\u003CNullable>enable\u003C\u002FNullable>` in .csproj). Use the compiler's flow analysis — don't add redundant null checks where the type system already guarantees non-null.\n\n**Use `??` for defaults and `?.` for optional chains:**\n\n```csharp\nvar name = user.DisplayName ?? user.Email ?? \"Anonymous\";\nvar city = user.Address?.City;\n```\n\n**Use `??=` for lazy initialization:**\n\n```csharp\n_cache ??= new Dictionary\u003Cstring, object>();\n```\n\n**Guard clause pattern for required non-null arguments:**\n\n```csharp\npublic UserService(IUserRepository repository, ILogger\u003CUserService> logger)\n{\n    _repository = repository ?? throw new ArgumentNullException(nameof(repository));\n    _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n}\n```\n\nWith C# 11+ and nullable enabled, prefer `required` keyword or primary constructors over null checks for constructor injection when the DI container guarantees non-null.\n\nC# 11+: prefer `required` properties with object initializers when the DI container guarantees non-null:\n\n```csharp\npublic sealed class UserService\n{\n    public required IUserRepository Repository { get; init; }\n    public required ILogger\u003CUserService> Logger { get; init; }\n}\n```\n\nC# 14: use the `field` keyword in property accessors to add validation without declaring an explicit backing field:\n\n```csharp\npublic string Email\n{\n    get;\n    set => field = !string.IsNullOrWhiteSpace(value)\n        ? value\n        : throw new ArgumentException(\"Email required\");\n}\n```\n\n## Pattern matching\n\nUse switch expressions for exhaustive branching. Clearer than if\u002Felif chains for type checks, property destructuring, and value mapping.\n\n```csharp\nvar message = result switch\n{\n    { IsSuccess: true, Value: var v } => $\"Got {v}\",\n    { Error: NotFoundError e } => $\"{e.Resource} not found\",\n    { Error: ValidationError e } => $\"Invalid: {string.Join(\", \", e.Errors)}\",\n    _ => \"Unknown error\"\n};\n```\n\nProperty patterns for conditional logic:\n\n```csharp\nif (order is { Status: OrderStatus.Shipped, TrackingNumber: not null } shipped)\n{\n    NotifyCustomer(shipped.TrackingNumber);\n}\n```\n\nRelational and logical patterns:\n\n```csharp\nvar tier = score switch\n{\n    >= 90 => \"Gold\",\n    >= 70 => \"Silver\",\n    >= 50 => \"Bronze\",\n    _ => \"None\"\n};\n```\n\nNull-conditional assignment (C# 14):\n\n```csharp\n\u002F\u002F Before C# 14:\nif (customer is not null) { customer.Order = GetCurrentOrder(); }\n\n\u002F\u002F C# 14:\ncustomer?.Order = GetCurrentOrder();\n```\n\nThe right side is evaluated only when the left is non-null.\n\n## Data modeling\n\n| Use Case | Choice | Reason |\n|----------|--------|--------|\n| API request\u002Fresponse DTOs | record | Immutable, value equality, concise syntax |\n| Configuration | record or POCO + IOptions\u003CT> | Framework support, binding |\n| Domain entities with identity | class | Reference equality, mutable state |\n| Simple value objects | readonly record struct | Stack-allocated, no GC pressure, value semantics |\n\nRecords for DTOs:\n\n```csharp\npublic sealed record CreateUserRequest(string Email, string Name);\n\npublic sealed record UserResponse(int Id, string Email, string Name);\n```\n\nPrimary constructors (C# 12) for service classes:\n\n```csharp\npublic sealed class UserService(IUserRepository repository, ILogger\u003CUserService> logger)\n{\n    public async Task\u003CUser> GetByIdAsync(int id, CancellationToken ct)\n    {\n        logger.LogDebug(\"Fetching user {UserId}\", id);\n        return await repository.GetByIdAsync(id, ct)\n            ?? throw new NotFoundException(\"User\", id);\n    }\n}\n```\n\nUse `init` properties when you need object initializer syntax with immutability:\n\n```csharp\npublic sealed class PaginationOptions\n{\n    public int Page { get; init; } = 1;\n    public int PageSize { get; init; } = 20;\n}\n```\n\n## Dependency injection\n\nConstructor injection. Dependencies are explicit and testable.\n\n```csharp\npublic sealed class OrderService(\n    IOrderRepository repository,\n    IPaymentClient payments,\n    ILogger\u003COrderService> logger)\n{\n    \u002F\u002F ...\n}\n```\n\n**Service lifetimes:**\n- **Transient** — lightweight, stateless services. New instance per injection.\n- **Scoped** — per-request state (DbContext, unit of work, caller context). One instance per HTTP request.\n- **Singleton** — thread-safe shared state (caches, configuration, HTTP client factories). One instance for app lifetime.\n\nMatch the project's DI container (Microsoft.Extensions.DependencyInjection, Autofac, etc.). Don't mix container-specific APIs across the codebase.\n\n**Register by interface, not concrete type:**\n\n```csharp\nservices.AddScoped\u003CIUserRepository, UserRepository>();\nservices.AddSingleton\u003CICacheService, RedisCacheService>();\n```\n\n## Enums\n\nUse enums for known fixed value sets. Don't use raw strings or magic numbers.\n\n```csharp\npublic enum OrderStatus\n{\n    Pending,\n    Confirmed,\n    Shipped,\n    Delivered,\n    Cancelled\n}\n```\n\nFor enums that need string serialization (APIs, databases), configure the JSON serializer to use string names rather than integer values. Don't scatter `ToString()` \u002F `Enum.Parse()` calls through business logic.\n\n## Imports\n\nUse `global using` directives (C# 10+) in a single `GlobalUsings.cs` file for project-wide imports. Don't duplicate common usings across every file. Match existing project convention — if there's no `GlobalUsings.cs`, use regular per-file usings.\n\nOrder: `System.*`, third-party, project namespaces. Let the IDE\u002Fformatter sort them.\n\n## Logging\n\nUse `ILogger\u003CT>` with structured logging. Use message templates with named placeholders — never string interpolation:\n\n```csharp\n\u002F\u002F Wrong — interpolation defeats structured logging\nlogger.LogInformation($\"User {userId} created order {orderId}\");\n\n\u002F\u002F Correct — structured, searchable, parameterized\nlogger.LogInformation(\"User {UserId} created order {OrderId}\", userId, orderId);\n```\n\nFor hot paths, use `LoggerMessage.Define` to avoid allocation:\n\n```csharp\nprivate static readonly Action\u003CILogger, int, Exception?> LogUserCreated =\n    LoggerMessage.Define\u003Cint>(LogLevel.Information, new EventId(1), \"User {UserId} created\");\n\n\u002F\u002F Usage\nLogUserCreated(logger, user.Id, null);\n```\n\nOr with .NET 6+ source generators:\n\n```csharp\n[LoggerMessage(Level = LogLevel.Information, Message = \"User {UserId} created\")]\nprivate static partial void LogUserCreated(ILogger logger, int userId);\n```\n\n## Testing\n\nMatch the project's test runner (xUnit, NUnit, MSTest) and mocking library (Moq, NSubstitute, FakeItEasy).\n\nWhen to mock: external HTTP APIs, databases, third-party services, and anything with side effects or costs. When to use real instances: pure logic, in-memory implementations, value objects.\n\nTest behavior, not implementation — test what a method returns or what side effects it produces, not how it internally works.\n\n```csharp\n[Test]\npublic async Task GetUser_WhenExists_ReturnsUser()\n{\n    \u002F\u002F Arrange\n    var repository = Substitute.For\u003CIUserRepository>();\n    repository.GetByIdAsync(42, Arg.Any\u003CCancellationToken>())\n        .Returns(new User { Id = 42, Name = \"Alice\" });\n    var service = new UserService(repository, NullLogger\u003CUserService>.Instance);\n\n    \u002F\u002F Act\n    var result = await service.GetByIdAsync(42, CancellationToken.None);\n\n    \u002F\u002F Assert\n    Assert.That(result.Name, Is.EqualTo(\"Alice\"));\n}\n```\n","# C# Coding\n\nMatch the project's existing conventions. When uncertain, read 2-3 existing files to infer the local style. Check `.csproj` for `TargetFramework` (`net10.0` LTS or `net9.0` STS in 2026), C# `LangVersion` (default `latest`; assume C# 14 on .NET 10), nullable settings, and analyzer config. These defaults apply only when the project has no established convention.\n\n## Never rules\n\nThese are unconditional. They prevent bugs and vulnerabilities regardless of project style.\n\n- **Never `catch { }` or `catch (Exception) { }` without rethrow or logging.** Broad catches silently swallow bugs — a NullReferenceException from a typo looks the same as a transient network failure. Catch specific exception types. If you must catch broadly at a boundary, always log and rethrow or convert to a meaningful error.\n- **Never `throw ex`** — use `throw` or `throw new XException(\"msg\", ex)`. `throw ex` resets the stack trace, destroying the origin of the error. You'll spend hours debugging something the original stack trace would have shown instantly.\n- **Never `DateTime.Now`** — use `DateTime.UtcNow` or `DateTimeOffset.UtcNow`. `DateTime.Now` produces local time that varies by server timezone and breaks across DST transitions. `DateTimeOffset` is preferred when the timezone context matters.\n- **Never `async void`** — except for event handlers. `async void` methods cannot be awaited, their exceptions crash the process unobserved, and they break structured error handling. Use `async Task` instead.\n- **Never `.Result`, `.Wait()`, or `.GetAwaiter().GetResult()` on tasks** — these block the calling thread and cause deadlocks in ASP.NET Core and UI contexts. Use `await` instead. If you're in a sync context that genuinely cannot be made async, use `Task.Run(() => AsyncMethod()).GetAwaiter().GetResult()` as a last resort with a comment explaining why.\n- **Never `Random` for security** — `Random` is not cryptographically secure and is predictable. Use `RandomNumberGenerator.GetBytes()`, `RandomNumberGenerator.GetInt32()`, or `Convert.ToHexString(RandomNumberGenerator.GetBytes(n))` for tokens, keys, session IDs.\n- **Never string interpolation or concatenation in SQL** — use parameterized queries only. `$\"SELECT * FROM users WHERE id = {uid}\"` is always a SQL injection vulnerability. Use `@param` placeholders with `SqlCommand.Parameters` or your ORM's parameterization.\n- **Never `GC.Collect()`** — the GC is self-tuning. Forcing collection hurts performance in nearly all cases by promoting short-lived objects to higher generations. If you think you need it, you have a design problem to fix instead.\n- **Never mutable static fields** — statics are shared across all threads. Mutable statics cause race conditions that are extremely hard to reproduce and debug. Use `IOptions\u003CT>`, dependency injection, or `ConcurrentDictionary` if shared state is genuinely needed.\n- **Never `+` string concatenation in loops** — use `StringBuilder`. Strings are immutable in C#, so each `+` allocates a new string and copies all previous content — O(n^2) at scale. At 10k iterations this turns milliseconds into seconds.\n- **Never `dynamic` for typed data** — `dynamic` bypasses compile-time type checking, turns type errors into runtime exceptions, and kills IntelliSense. Use generics, interfaces, or pattern matching instead. Reserve `dynamic` for COM interop or truly dynamic scenarios.\n- **Never `Thread.Sleep()` in async code** — use `await Task.Delay()`. `Thread.Sleep` blocks the thread pool thread, starving other async operations. In ASP.NET Core this can exhaust the thread pool under load.\n\n## Error handling\n\nUse `throw` (not `throw ex`) when re-throwing to preserve the original stack trace. Wrap with inner exception when converting exception types at boundaries:\n\n```csharp\ntry\n{\n    var result = await httpClient.GetAsync(url, cancellationToken);\n    result.EnsureSuccessStatusCode();\n}\ncatch (HttpRequestException ex)\n{\n    throw new ServiceUnavailableException($\"Failed to reach {url}\", ex);\n}\n```\n\nUse exception filters (`when`) to catch conditionally without unwinding the stack:\n\n```csharp\ncatch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)\n{\n    return null;\n}\ncatch (HttpRequestException ex) when (ex.StatusCode >= HttpStatusCode.InternalServerError)\n{\n    logger.LogWarning(ex, \"Transient server error from {Url}\", url);\n    throw;\n}\n```\n\nCreate custom exception types when callers need to distinguish failure modes:\n\n```csharp\npublic class AppException : Exception\n{\n    public AppException(string message) : base(message) { }\n    public AppException(string message, Exception inner) : base(message, inner) { }\n}\n\npublic class NotFoundException : AppException\n{\n    public string Resource { get; }\n    public object Id { get; }\n\n    public NotFoundException(string resource, object id)\n        : base($\"{resource} not found: {id}\")\n    {\n        Resource = resource;\n        Id = id;\n    }\n}\n```\n\n## Resource cleanup\n\nUse `using` declarations for anything that implements `IDisposable` or `IAsyncDisposable`. Never instantiate `HttpClient`, database connections, streams, or similar without `using` or explicit `finally` cleanup.\n\n```csharp\n\u002F\u002F C# 8+ using declaration — disposed at end of scope\nusing var stream = File.OpenRead(path);\nusing var reader = new StreamReader(stream);\nvar content = await reader.ReadToEndAsync(cancellationToken);\n```\n\nFor async disposables:\n\n```csharp\nawait using var connection = new SqlConnection(connectionString);\nawait connection.OpenAsync(cancellationToken);\n```\n\nFor multiple resources or complex lifecycles, use explicit `try\u002Ffinally`:\n\n```csharp\nvar connection = new SqlConnection(connectionString);\ntry\n{\n    await connection.OpenAsync(cancellationToken);\n    \u002F\u002F work\n}\nfinally\n{\n    await connection.DisposeAsync();\n}\n```\n\nWhen implementing `IDisposable`, follow the pattern only if you hold unmanaged resources or own other disposables. Don't implement `IDisposable` on classes that don't own anything disposable — it adds ceremony for no benefit.\n\n## Async patterns\n\n**Always pass `CancellationToken` through the call chain.** Accept it as the last parameter and forward it to every async API. Omitting it means your code cannot be cancelled, leading to wasted resources and hung requests.\n\n```csharp\npublic async Task\u003CUser> GetUserAsync(int id, CancellationToken cancellationToken = default)\n{\n    var response = await _httpClient.GetAsync($\"\u002Fusers\u002F{id}\", cancellationToken);\n    response.EnsureSuccessStatusCode();\n    return await response.Content.ReadFromJsonAsync\u003CUser>(cancellationToken: cancellationToken)\n        ?? throw new NotFoundException(\"User\", id);\n}\n```\n\n**Prefer `Task` over `ValueTask`** unless profiling shows allocation pressure from a hot path that frequently completes synchronously. `ValueTask` has restrictions (can only be awaited once, no concurrent awaits) that make it error-prone as a default choice.\n\n**Use `ConfigureAwait(false)` in library code** (NuGet packages, shared class libraries) to avoid deadlocks in non-ASP.NET Core consumers. In ASP.NET Core application code, it's unnecessary — the default `SynchronizationContext` is null.\n\n**Use `Task.WhenAll` for independent concurrent work:**\n\n```csharp\nvar usersTask = GetUsersAsync(cancellationToken);\nvar ordersTask = GetOrdersAsync(cancellationToken);\n\nawait Task.WhenAll(usersTask, ordersTask);\n\nvar users = await usersTask;\nvar orders = await ordersTask;\n```\n\n**Never use `async` on a method that just returns another task.** Remove the state machine overhead:\n\n```csharp\n\u002F\u002F Wrong — unnecessary async state machine\npublic async Task\u003CUser> GetUserAsync(int id, CancellationToken ct)\n    => await _repository.GetByIdAsync(id, ct);\n\n\u002F\u002F Correct — direct passthrough\npublic Task\u003CUser> GetUserAsync(int id, CancellationToken ct)\n    => _repository.GetByIdAsync(id, ct);\n```\n\nException: keep `async`\u002F`await` when you need `using`, `try\u002Fcatch`, or when the method does work before\u002Fafter the awaited call.\n\n## C# 13 params collections\n\n`params` is no longer limited to arrays. Use `params ReadOnlySpan\u003CT>` for zero-allocation variadic APIs; use `params IEnumerable\u003CT>` when the caller may pass a lazy source:\n\n```csharp\npublic static int Sum(params ReadOnlySpan\u003Cint> values)\n{\n    var total = 0;\n    foreach (var v in values) total += v;\n    return total;\n}\n\nSum(1, 2, 3); \u002F\u002F no heap allocation\n```\n\nFor shared-state synchronization, prefer `System.Threading.Lock` over `lock (someObject)` where available:\n\n```csharp\nprivate readonly Lock _gate = new();\n\nvoid AppendSafely(string item)\n{\n    using (_gate.EnterScope()) { _items.Add(item); }\n}\n```\n\n## Nullability\n\nEnable nullable reference types (`\u003CNullable>enable\u003C\u002FNullable>` in .csproj). Use the compiler's flow analysis — don't add redundant null checks where the type system already guarantees non-null.\n\n**Use `??` for defaults and `?.` for optional chains:**\n\n```csharp\nvar name = user.DisplayName ?? user.Email ?? \"Anonymous\";\nvar city = user.Address?.City;\n```\n\n**Use `??=` for lazy initialization:**\n\n```csharp\n_cache ??= new Dictionary\u003Cstring, object>();\n```\n\n**Guard clause pattern for required non-null arguments:**\n\n```csharp\npublic UserService(IUserRepository repository, ILogger\u003CUserService> logger)\n{\n    _repository = repository ?? throw new ArgumentNullException(nameof(repository));\n    _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n}\n```\n\nWith C# 11+ and nullable enabled, prefer `required` keyword or primary constructors over null checks for constructor injection when the DI container guarantees non-null.\n\nC# 11+: prefer `required` properties with object initializers when the DI container guarantees non-null:\n\n```csharp\npublic sealed class UserService\n{\n    public required IUserRepository Repository { get; init; }\n    public required ILogger\u003CUserService> Logger { get; init; }\n}\n```\n\nC# 14: use the `field` keyword in property accessors to add validation without declaring an explicit backing field:\n\n```csharp\npublic string Email\n{\n    get;\n    set => field = !string.IsNullOrWhiteSpace(value)\n        ? value\n        : throw new ArgumentException(\"Email required\");\n}\n```\n\n## Pattern matching\n\nUse switch expressions for exhaustive branching. Clearer than if\u002Felif chains for type checks, property destructuring, and value mapping.\n\n```csharp\nvar message = result switch\n{\n    { IsSuccess: true, Value: var v } => $\"Got {v}\",\n    { Error: NotFoundError e } => $\"{e.Resource} not found\",\n    { Error: ValidationError e } => $\"Invalid: {string.Join(\", \", e.Errors)}\",\n    _ => \"Unknown error\"\n};\n```\n\nProperty patterns for conditional logic:\n\n```csharp\nif (order is { Status: OrderStatus.Shipped, TrackingNumber: not null } shipped)\n{\n    NotifyCustomer(shipped.TrackingNumber);\n}\n```\n\nRelational and logical patterns:\n\n```csharp\nvar tier = score switch\n{\n    >= 90 => \"Gold\",\n    >= 70 => \"Silver\",\n    >= 50 => \"Bronze\",\n    _ => \"None\"\n};\n```\n\nNull-conditional assignment (C# 14):\n\n```csharp\n\u002F\u002F Before C# 14:\nif (customer is not null) { customer.Order = GetCurrentOrder(); }\n\n\u002F\u002F C# 14:\ncustomer?.Order = GetCurrentOrder();\n```\n\nThe right side is evaluated only when the left is non-null.\n\n## Data modeling\n\n| Use Case | Choice | Reason |\n|----------|--------|--------|\n| API request\u002Fresponse DTOs | record | Immutable, value equality, concise syntax |\n| Configuration | record or POCO + IOptions\u003CT> | Framework support, binding |\n| Domain entities with identity | class | Reference equality, mutable state |\n| Simple value objects | readonly record struct | Stack-allocated, no GC pressure, value semantics |\n\nRecords for DTOs:\n\n```csharp\npublic sealed record CreateUserRequest(string Email, string Name);\n\npublic sealed record UserResponse(int Id, string Email, string Name);\n```\n\nPrimary constructors (C# 12) for service classes:\n\n```csharp\npublic sealed class UserService(IUserRepository repository, ILogger\u003CUserService> logger)\n{\n    public async Task\u003CUser> GetByIdAsync(int id, CancellationToken ct)\n    {\n        logger.LogDebug(\"Fetching user {UserId}\", id);\n        return await repository.GetByIdAsync(id, ct)\n            ?? throw new NotFoundException(\"User\", id);\n    }\n}\n```\n\nUse `init` properties when you need object initializer syntax with immutability:\n\n```csharp\npublic sealed class PaginationOptions\n{\n    public int Page { get; init; } = 1;\n    public int PageSize { get; init; } = 20;\n}\n```\n\n## Dependency injection\n\nConstructor injection. Dependencies are explicit and testable.\n\n```csharp\npublic sealed class OrderService(\n    IOrderRepository repository,\n    IPaymentClient payments,\n    ILogger\u003COrderService> logger)\n{\n    \u002F\u002F ...\n}\n```\n\n**Service lifetimes:**\n- **Transient** — lightweight, stateless services. New instance per injection.\n- **Scoped** — per-request state (DbContext, unit of work, caller context). One instance per HTTP request.\n- **Singleton** — thread-safe shared state (caches, configuration, HTTP client factories). One instance for app lifetime.\n\nMatch the project's DI container (Microsoft.Extensions.DependencyInjection, Autofac, etc.). Don't mix container-specific APIs across the codebase.\n\n**Register by interface, not concrete type:**\n\n```csharp\nservices.AddScoped\u003CIUserRepository, UserRepository>();\nservices.AddSingleton\u003CICacheService, RedisCacheService>();\n```\n\n## Enums\n\nUse enums for known fixed value sets. Don't use raw strings or magic numbers.\n\n```csharp\npublic enum OrderStatus\n{\n    Pending,\n    Confirmed,\n    Shipped,\n    Delivered,\n    Cancelled\n}\n```\n\nFor enums that need string serialization (APIs, databases), configure the JSON serializer to use string names rather than integer values. Don't scatter `ToString()` \u002F `Enum.Parse()` calls through business logic.\n\n## Imports\n\nUse `global using` directives (C# 10+) in a single `GlobalUsings.cs` file for project-wide imports. Don't duplicate common usings across every file. Match existing project convention — if there's no `GlobalUsings.cs`, use regular per-file usings.\n\nOrder: `System.*`, third-party, project namespaces. Let the IDE\u002Fformatter sort them.\n\n## Logging\n\nUse `ILogger\u003CT>` with structured logging. Use message templates with named placeholders — never string interpolation:\n\n```csharp\n\u002F\u002F Wrong — interpolation defeats structured logging\nlogger.LogInformation($\"User {userId} created order {orderId}\");\n\n\u002F\u002F Correct — structured, searchable, parameterized\nlogger.LogInformation(\"User {UserId} created order {OrderId}\", userId, orderId);\n```\n\nFor hot paths, use `LoggerMessage.Define` to avoid allocation:\n\n```csharp\nprivate static readonly Action\u003CILogger, int, Exception?> LogUserCreated =\n    LoggerMessage.Define\u003Cint>(LogLevel.Information, new EventId(1), \"User {UserId} created\");\n\n\u002F\u002F Usage\nLogUserCreated(logger, user.Id, null);\n```\n\nOr with .NET 6+ source generators:\n\n```csharp\n[LoggerMessage(Level = LogLevel.Information, Message = \"User {UserId} created\")]\nprivate static partial void LogUserCreated(ILogger logger, int userId);\n```\n\n## Testing\n\nMatch the project's test runner (xUnit, NUnit, MSTest) and mocking library (Moq, NSubstitute, FakeItEasy).\n\nWhen to mock: external HTTP APIs, databases, third-party services, and anything with side effects or costs. When to use real instances: pure logic, in-memory implementations, value objects.\n\nTest behavior, not implementation — test what a method returns or what side effects it produces, not how it internally works.\n\n```csharp\n[Test]\npublic async Task GetUser_WhenExists_ReturnsUser()\n{\n    \u002F\u002F Arrange\n    var repository = Substitute.For\u003CIUserRepository>();\n    repository.GetByIdAsync(42, Arg.Any\u003CCancellationToken>())\n        .Returns(new User { Id = 42, Name = \"Alice\" });\n    var service = new UserService(repository, NullLogger\u003CUserService>.Instance);\n\n    \u002F\u002F Act\n    var result = await service.GetByIdAsync(42, CancellationToken.None);\n\n    \u002F\u002F Assert\n    Assert.That(result.Name, Is.EqualTo(\"Alice\"));\n}\n```\n",{"name":5,"description":7},"main","08c084f718b2b842cd53622ce0b1a1fb2888ccef","test\u002Fcast-fixtures\u002Fcodex-cli\u002Fregression\u002Fjust-works\u002F.codex\u002Fskills\u002Fcsharp-coding",1,"https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai","2026-07-15 23:48:12",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add tamarillo-ai\u002Ftheta --skill csharp-coding",{"tool":37,"command":38},"bunx","bunx skills add tamarillo-ai\u002Ftheta --skill csharp-coding",{"tool":40,"command":41},"pnpm","pnpm dlx skills add tamarillo-ai\u002Ftheta --skill csharp-coding","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcodex-cli\u002Fregression\u002Fjust-works\u002F.codex\u002Fskills\u002Fcsharp-coding\u002FSKILL.md",true,[],[46,53,60,68,75,82],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M74FCAJ0RRFRJRQES26329E7","deploy-app","Deploy the application to staging or production environments.","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcursor\u002Fskills\u002Fbasic\u002F.cursor\u002Fskills\u002Fdeploy-app\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M74FC8GPJGCS0KTGKS1CJZZS","deploy","Deploy the application to environments.","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcursor\u002Fcombined\u002Ffull-config\u002F.cursor\u002Fskills\u002Fdeploy\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":64,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M74FC5RT3VTNZEK1F7NX5380","building-native-ui","Complete guide for building beautiful apps with Expo Router. Covers fundamentals, styling, components, navigation, animations, patterns, and native tabs.","MIT","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcopilot\u002Fskills\u002Fwith-references\u002F.github\u002Fskills\u002Fbuilding-native-ui\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M74FC1ZGP5R44HPGWWSW6P3B","create-section","Use when creating a new section for the AI Workshop presentation. Guides through title slide setup, layout choices, and content gathering. Activates when user wants to add a new topic section to the slideshow.","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcopilot\u002Fskills\u002Fbasic\u002F.github\u002Fskills\u002Fcreate-section\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M74FBZXSZ7GVP0HCGNR1BVNH","ship-checker","Run a full pre-ship review for this repo. Use when asked if a change is ready to deploy, publish, or ship.","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcopilot\u002Fcombined\u002Feverything\u002F.github\u002Fskills\u002Fship-checker\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M74FBY4N2E3ZERWBRM4S3DE6","lint-check","Run repository linters and report failures.","https:\u002F\u002Fgithub.com\u002Ftamarillo-ai\u002Ftheta\u002Fblob\u002Fmain\u002Ftest\u002Fcast-fixtures\u002Fcodex-cli\u002Fskills\u002Fagents-path\u002F.agents\u002Fskills\u002Flint-check\u002FSKILL.md",[],[]]