[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70FMEPB0ZNVDWGSSH7WQH3A":3,"skill-same:01M70FMEPB0ZNVDWGSSH7WQH3A":67},{"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":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":50,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M70FMEPB0ZNVDWGSSH7WQH3A","csharp-coding-standards",null,"Defines the C# coding standards, patterns, and conventions to be applied consistently across all C# projects. Rules cover naming, structure, async patterns, null handling, dependency injection, logging, result patterns, and formatting. Apply these rules uniformly in all production code.","linuxchata\u002Fai-playbook","linuxchata","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4677708?v=4","01M70FKZZ754E4J9YW50S4W529","LinuxChata","01M70FKZZWGNFS9T7BBZ490ZW1",7,"MIT","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002F.gemini\u002Fskills\u002Fcsharp-coding-standards\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"standards","coding standards","csharp","csharp coding standards","coding","dependency injection","logging","formatting","patterns","cover","dependency","result","across","code","C#","apply","Rules","injection","structure","projects","2026-11-10 10:12:30",false,"---\nname: csharp-coding-standards\ndescription: Defines the C# coding standards, patterns, and conventions to be applied consistently across all C# projects. Rules cover naming, structure, async patterns, null handling, dependency injection, logging, result patterns, and formatting. Apply these rules uniformly in all production code.\n---\n\n# C# Coding Standards\n\n## Description\n\nDefines the C# coding standards, patterns, and conventions to be applied consistently across all C# projects. Rules cover naming, structure, async patterns, null handling, dependency injection, logging, result patterns, and formatting. Apply these rules uniformly in all production code.\n\n---\n\n## 1. File & Namespace Structure\n\n### 1.1 File-Scoped Namespaces\n\nAlways use **file-scoped namespaces**:\n\n```csharp\n\u002F\u002F ✅ Correct\nnamespace MyApp.Core.Validators;\n\ninternal class OrderValidator { }\n\n\u002F\u002F ❌ Wrong\nnamespace MyApp.Core.Validators\n{\n    internal class OrderValidator { }\n}\n```\n\n### 1.2 Using Directives\n\n- Place `using` directives **outside** the namespace.\n- Group: System namespaces first, then others ordered alphabetically – separated by a blank line.\n- Use implicit usings where available; add explicit usings only when needed for disambiguation.\n\n```csharp\nusing System.Text;\nusing System.Text.Json;\nusing Microsoft.Extensions.Logging;\nusing MyApp.Core.Abstractions;\nusing MyApp.Domain;\n```\n\n### 1.3 One Type Per File\n\nEach file contains exactly one top-level type. The file name must match the type name exactly.\n\n---\n\n## 2. Naming Conventions\n\n### 2.1 Types\n\n| Kind | Convention | Example |\n|---|---|---|\n| Classes | PascalCase | `OrderValidator`, `UserService` |\n| Interfaces | `I` prefix + PascalCase | `IOrderRepository`, `IUserService` |\n| Enums | PascalCase | `OrderStatus`, `PaymentMethod` |\n| Structs | PascalCase | `Money`, `DateRange` |\n| Records | PascalCase | `AppConfiguration`, `UserSettings` |\n\n### 2.2 Members\n\n| Kind | Convention | Example |\n|---|---|---|\n| Public properties | PascalCase | `CreatedAt`, `TotalAmount` |\n| Public methods | PascalCase | `CreateOrder`, `ValidatePayment` |\n| Private fields | `_camelCase` (underscore prefix) | `_repository`, `_logger` |\n| Constants | PascalCase | `DefaultTimeout`, `MaxRetryCount` |\n| Local variables | camelCase | `orderId`, `serializedData` |\n| Method parameters | camelCase | `cancellationToken`, `userId` |\n| Lambda parameters | Short camelCase | `x =>`, `e =>`, `o =>` |\n\n### 2.3 Async Methods\n\n> **All async methods MUST end with the `Async` suffix without exception.**\n\n```csharp\n\u002F\u002F ✅ Correct\npublic async Task\u003COrder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);\n\n\u002F\u002F ❌ Wrong – missing Async suffix\npublic async Task\u003COrder?> GetById(Guid id, CancellationToken cancellationToken);\n```\n\nThis applies to:\n- Interface declarations\n- Public and internal implementation methods\n- Private helper methods\n\n---\n\n## 3. Access Modifiers & Sealed Classes\n\n### 3.1 Least Privilege\n\n- Prefer `internal` for implementation types; use `public` only for types that are part of the public API surface.\n- Implementation classes registered via DI should be `internal sealed`.\n- Types that implement a public interface and form the public API are `public sealed`.\n\n```csharp\n\u002F\u002F ✅ Correct: public sealed for types exposed via public interface\npublic sealed class OrderService : IOrderService { }\n\n\u002F\u002F ✅ Correct: internal sealed for infrastructure implementations\ninternal sealed class SqlOrderRepository : IOrderRepository { }\n```\n\n### 3.2 `sealed` Usage\n\nMark classes `sealed` by default unless inheritance is explicitly required. This prevents unintended derivation and enables JIT optimizations.\n\n---\n\n## 4. Null Handling & Defensive Programming\n\n### 4.1 Nullable Reference Types\n\n- Enable nullable context for all projects (`\u003CNullable>enable\u003C\u002FNullable>`).\n- Annotate all nullable references explicitly with `?`.\n- Avoid the null-forgiving operator (`!`) without an inline comment explaining why it is safe.\n- Prefer early-return guards over deeply nested null checks.\n\n```csharp\n\u002F\u002F ✅ Early return guard\nif (id is null || id.Length == 0)\n{\n    return null;\n}\n```\n\n### 4.2 Argument Validation\n\nUse modern `ArgumentNullException` helpers for public\u002Finternal method boundaries:\n\n```csharp\n\u002F\u002F ✅ Correct\nArgumentNullException.ThrowIfNull(order);\nArgumentNullException.ThrowIfNullOrEmpty(order.UserName);\n```\n\n### 4.3 Null Propagation & Coalescing\n\nPrefer `?.` and `??` \u002F `??=` over verbose null checks in expressions:\n\n```csharp\n\u002F\u002F ✅ Correct\nreturn items?.Select(x => x.ToDto()).ToArray();\n\nvar name = input?.Trim() ?? string.Empty;\n```\n\n---\n\n## 5. Constructor Injection & Dependency Injection\n\n### 5.1 Constructor Injection\n\nAlways inject dependencies via the constructor. Store them as `private readonly` fields prefixed with `_`.\n\n```csharp\nprivate readonly IOrderRepository _orderRepository;\nprivate readonly ILogger\u003COrderService> _logger;\n\npublic OrderService(IOrderRepository orderRepository, ILogger\u003COrderService> logger)\n{\n    _orderRepository = orderRepository;\n    _logger = logger;\n}\n```\n\n### 5.2 Options Pattern\n\nAccess configuration via `IOptions\u003CT>`. Extract `.Value` in the constructor and store as a field – do not access `.Value` repeatedly at call sites.\n\n```csharp\nprivate readonly AppConfiguration _configuration;\n\npublic OrderService(IOptions\u003CAppConfiguration> options)\n{\n    _configuration = options.Value;\n}\n```\n\n### 5.3 DI Registration\n\nCentralize all service registrations in a dedicated `DependencyInjection.cs` static class with `IServiceCollection` extension methods.\n\n```csharp\npublic static class DependencyInjection\n{\n    public static void AddMyFeature(this IServiceCollection services, IConfiguration configuration)\n    {\n        services.AddTransient\u003CIOrderService, OrderService>();\n        services.AddKeyedTransient\u003CIPaymentStrategy, CreditCardStrategy>(\"creditcard\");\n    }\n}\n```\n\nLifetime guidance:\n- `AddTransient` – stateless, short-lived services.\n- `AddSingleton` – thread-safe, shared-state services (e.g., `TimeProvider`, static caches).\n- `AddKeyedTransient` \u002F `AddKeyedSingleton` – strategy-pattern registrations keyed by a discriminator.\n\n---\n\n## 6. Async \u002F Await\n\n### 6.1 Always Propagate CancellationToken\n\nEvery public and internal async method should accept a `CancellationToken` as its **last parameter**:\n\n```csharp\n\u002F\u002F ✅ Correct\nTask\u003COrder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);\nTask SaveAsync(Order order, CancellationToken cancellationToken);\n```\n\n### 6.2 No `ConfigureAwait(false)` in Application Code\n\nDo not use `.ConfigureAwait(false)` in application-layer and library code targeting ASP.NET Core. Reserve it only for low-level infrastructure libraries where synchronization context must be avoided explicitly.\n\n### 6.3 Never Use `async void`\n\nNever use `async void` except for event handlers. Always return `Task` or `Task\u003CT>`.\n\n### 6.4 Async Locks via SemaphoreSlim\n\nUse `SemaphoreSlim` for async-compatible critical sections. Always release in a `finally` block:\n\n```csharp\nprivate static readonly SemaphoreSlim Lock = new(1, 1);\n\nawait Lock.WaitAsync(cancellationToken);\ntry\n{\n    \u002F\u002F Critical section\n}\nfinally\n{\n    Lock.Release();\n}\n```\n\n### 6.5 Return Task Directly for Pass-Through Methods\n\nWhen a method only delegates to a single async call with no surrounding logic, return the `Task` directly to avoid an unnecessary state machine:\n\n```csharp\n\u002F\u002F ✅ Correct – no state machine overhead\nprivate Task\u003Cstring?> GetCachedValueAsync(string key, CancellationToken cancellationToken)\n{\n    return _cache.GetStringAsync(key, cancellationToken);\n}\n```\n\n---\n\n## 7. Result Pattern\n\n### 7.1 Internal Results\n\nDo not throw exceptions for expected, recoverable validation failures. Use typed result objects that carry success\u002Ffailure state and an optional message:\n\n```csharp\n\u002F\u002F Validator result (IsValid + Message)\npublic static ValidationResult Valid() => new(true);\npublic static ValidationResult Invalid(string message) => new(false, message);\n\n\u002F\u002F Handler\u002Foperation result (Value + HasError + Message)\npublic Result\u003CT> Execute(...)\n{\n    if (inputIsInvalid)\n        return new Result\u003CT>(\"Validation failed: input cannot be null\");\n\n    return new Result\u003CT>(computedValue);\n}\n```\n\n### 7.2 Public Results\n\nPublic-facing operation results use static factory methods for readability:\n\n```csharp\n\u002F\u002F ✅ Correct\nreturn OperationResult.Success();\nreturn OperationResult.Failure(\"The record was not found\");\n```\n\n### 7.3 Fail Fast, Return Early\n\nValidate all inputs at the top of the method. Return early on error. Do not let invalid state propagate deep into a method body.\n\n```csharp\nvar validation = _validator.Validate(request);\nif (!validation.IsValid)\n{\n    return OperationResult.Failure(validation.Message!);\n}\n\n\u002F\u002F proceed with valid data only\n```\n\n---\n\n## 8. Logging\n\n### 8.1 Structured Logging\n\nAlways use **named placeholder syntax** – never string interpolation in log messages:\n\n```csharp\n\u002F\u002F ✅ Correct\n_logger.LogWarning(\"Order '{OrderId}' was not found for user '{UserId}'\", orderId, userId);\n\n\u002F\u002F ❌ Wrong\n_logger.LogWarning($\"Order '{orderId}' was not found for user '{userId}'\");\n```\n\n### 8.2 Log Level Selection\n\n| Situation | Level |\n|---|---|\n| Normal successful operation | `LogDebug` |\n| Handled failure or unexpected but recoverable condition | `LogWarning` |\n| Unrecoverable exception or system error | `LogError` |\n| Sensitive \u002F PII data | Do not log – redact |\n\n### 8.3 Logger Injection\n\nAlways inject `ILogger\u003CT>` where `T` is the exact enclosing class. Do not share logger instances across types.\n\n---\n\n## 9. Collections & LINQ\n\n### 9.1 Collection Expressions\n\nUse C# 12+ collection expressions (`[]`) for empty collections and simple inline initialization:\n\n```csharp\n\u002F\u002F ✅ Correct\nstring[] tags = [];\nItems = existingItems ?? [],\nreturn [];\n```\n\n### 9.2 LINQ Style\n\n- Prefer **method syntax** over query syntax.\n- Chain transformations fluently (`.Where()`, `.Select()`, `.OrderBy()`) and materialize at the end with `.ToList()` or `.ToArray()`.\n- Avoid intermediate `.ToList()` calls mid-chain; defer materialization.\n\n```csharp\n\u002F\u002F ✅ Correct\nreturn orders\n    .Where(o => o.IsActive)\n    .Select(o => o.ToSummaryDto())\n    .ToArray();\n```\n\n### 9.3 Empty Collection Checks\n\nPrefer `.Length == 0` or `.Count == 0` over `!collection.Any()` in performance-sensitive paths.\n\n---\n\n## 10. Pattern Matching & Switch Expressions\n\nUse switch expressions for exhaustive value dispatch instead of chains of `if`\u002F`else if`:\n\n```csharp\n\u002F\u002F ✅ Correct\nvar label = status switch\n{\n    OrderStatus.Pending   => \"Awaiting confirmation\",\n    OrderStatus.Confirmed => \"Confirmed\",\n    OrderStatus.Shipped   => \"On the way\",\n    _                     => \"Unknown\",\n};\n```\n\nPrefer `is null` \u002F `is not null` over `== null` \u002F `!= null` for reference type null checks:\n\n```csharp\nif (order is null) { ... }\nif (result is not null) { ... }\n```\n\n---\n\n## 11. Domain Model Design\n\n### 11.1 Required Properties\n\nUse the `required` keyword for mandatory properties to enforce initialization at the call site:\n\n```csharp\npublic sealed class Order\n{\n    public required Guid Id { get; set; }\n    public required string CustomerName { get; set; }\n    public required decimal TotalAmount { get; set; }\n}\n```\n\n### 11.2 Sealed Domain Models\n\nSeal domain and result classes that are not designed for inheritance:\n\n```csharp\npublic sealed class Order { }\npublic sealed class OperationResult { }\n```\n\n---\n\n## 12. XML Documentation\n\n### 12.1 Public API\n\nAll `public` interfaces, classes, and their members must carry full XML doc comments:\n\n```csharp\n\u002F\u002F\u002F \u003Csummary>\n\u002F\u002F\u002F Retrieves an order by its unique identifier.\n\u002F\u002F\u002F \u003C\u002Fsummary>\n\u002F\u002F\u002F \u003Cparam name=\"id\">The unique identifier of the order.\u003C\u002Fparam>\n\u002F\u002F\u002F \u003Cparam name=\"cancellationToken\">A cancellation token.\u003C\u002Fparam>\n\u002F\u002F\u002F \u003Creturns>The order if found; otherwise, \u003Cc>null\u003C\u002Fc>.\u003C\u002Freturns>\nTask\u003COrder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);\n```\n\n### 12.2 Internal Types\n\nXML doc comments are optional on `internal` types but strongly encouraged for any non-trivial logic.\n\n---\n\n## 13. Constants & Magic Values\n\n### 13.1 Named Constants\n\nNever use magic numbers or strings inline. Declare them as `private const` or `private static readonly`:\n\n```csharp\nprivate const int MaxRetryCount = 3;\nprivate const string DefaultCacheKeyPrefix = \"order\";\nprivate const int DefaultTimeoutSeconds = 60;\n```\n\n### 13.2 Constants Organization\n\nGroup related constants into dedicated static classes inside a `Constants\u002F` folder. One class per logical domain (e.g., `CacheKeys`, `HeaderNames`, `ErrorMessages`).\n\n---\n\n## 14. Formatting\n\n### 14.1 Indentation & Whitespace\n\n- **Indent size**: 4 spaces – no tabs.\n- **Line endings**: CRLF.\n- One blank line between method bodies.\n- One blank line between property groups.\n\n### 14.2 Braces\n\nAlways use braces, even for single-line `if` \u002F `else` \u002F `for` \u002F `foreach` bodies:\n\n```csharp\n\u002F\u002F ✅ Correct\nif (order is null)\n{\n    return OperationResult.Failure(\"Order not found\");\n}\n\n\u002F\u002F ❌ Wrong\nif (order is null)\n    return OperationResult.Failure(\"Order not found\");\n```\n\n### 14.3 Expression-Bodied Members\n\n| Member Type | Preferred Style |\n|---|---|\n| Properties | Expression-bodied (`=>`) allowed |\n| Short indexers | Expression-bodied allowed |\n| Methods | **Block body** preferred |\n| Constructors | **Block body** required |\n| Lambdas | Expression-bodied preferred |\n| Local functions | Block body preferred |\n\n### 14.4 Long Parameter Lists\n\nBreak constructor or method parameters onto separate lines when there are 3 or more:\n\n```csharp\npublic OrderService(\n    IOrderRepository orderRepository,\n    IPaymentService paymentService,\n    IOptions\u003CAppConfiguration> options,\n    ILogger\u003COrderService> logger)\n```\n\n### 14.5 Object & Collection Initializers\n\nAlways use object initializer syntax for domain objects and DTOs. Include a trailing comma after the last member:\n\n```csharp\nvar order = new Order\n{\n    Id = Guid.NewGuid(),\n    CustomerName = request.CustomerName.Trim(),\n    TotalAmount = request.Amount,\n    Tags = [],\n};\n```\n\n---\n\n## 15. Extension Methods\n\n- Place extension methods in a dedicated `Extensions\u002F` folder.\n- One static class per extended type or logical concept: `StringExtensions`, `EnumExtensions`, `DateTimeExtensions`.\n- All extension classes are `public static`.\n- Generic constraints should be as tight as the use case requires.\n\n```csharp\npublic static class EnumExtensions\n{\n    public static string GetSerializedValue\u003CT>(this T value) where T : Enum { ... }\n    public static T ToEnum\u003CT>(this string value) where T : struct, Enum { ... }\n    public static T? ToNullableEnum\u003CT>(this string? value) where T : struct, Enum { ... }\n}\n```\n\n---\n\n## 16. Security-Sensitive Code\n\n- Never log raw sensitive bytes, private key material, passwords, tokens, or PII.\n- Use constant-time or span-based byte array comparison helpers to prevent timing attacks – never use `==` or `SequenceEqual` for security-critical comparisons.\n- Always sanitize user input (`.Trim()`) before storing, comparing, or forwarding.\n- Validate all untrusted input at the boundary layer – do not rely on inner layers to catch invalid data.\n\n---\n\n## Quick Reference Checklist\n\nBefore submitting any C# file, verify:\n\n- [ ] File-scoped namespace used\n- [ ] All async methods end with the `Async` suffix\n- [ ] `CancellationToken` is the last parameter of every async method\n- [ ] Nullable reference types annotated correctly – no unexplained `!`\n- [ ] Braces on every `if` \u002F `else` \u002F `for` \u002F `foreach`\n- [ ] No magic numbers or strings – all constants named\n- [ ] Structured logging – no string interpolation in log calls\n- [ ] Public API members have XML documentation\n- [ ] Result pattern used instead of exceptions for expected failures\n","# C# Coding Standards\n\n## Description\n\nDefines the C# coding standards, patterns, and conventions to be applied consistently across all C# projects. Rules cover naming, structure, async patterns, null handling, dependency injection, logging, result patterns, and formatting. Apply these rules uniformly in all production code.\n\n---\n\n## 1. File & Namespace Structure\n\n### 1.1 File-Scoped Namespaces\n\nAlways use **file-scoped namespaces**:\n\n```csharp\n\u002F\u002F ✅ Correct\nnamespace MyApp.Core.Validators;\n\ninternal class OrderValidator { }\n\n\u002F\u002F ❌ Wrong\nnamespace MyApp.Core.Validators\n{\n    internal class OrderValidator { }\n}\n```\n\n### 1.2 Using Directives\n\n- Place `using` directives **outside** the namespace.\n- Group: System namespaces first, then others ordered alphabetically – separated by a blank line.\n- Use implicit usings where available; add explicit usings only when needed for disambiguation.\n\n```csharp\nusing System.Text;\nusing System.Text.Json;\nusing Microsoft.Extensions.Logging;\nusing MyApp.Core.Abstractions;\nusing MyApp.Domain;\n```\n\n### 1.3 One Type Per File\n\nEach file contains exactly one top-level type. The file name must match the type name exactly.\n\n---\n\n## 2. Naming Conventions\n\n### 2.1 Types\n\n| Kind | Convention | Example |\n|---|---|---|\n| Classes | PascalCase | `OrderValidator`, `UserService` |\n| Interfaces | `I` prefix + PascalCase | `IOrderRepository`, `IUserService` |\n| Enums | PascalCase | `OrderStatus`, `PaymentMethod` |\n| Structs | PascalCase | `Money`, `DateRange` |\n| Records | PascalCase | `AppConfiguration`, `UserSettings` |\n\n### 2.2 Members\n\n| Kind | Convention | Example |\n|---|---|---|\n| Public properties | PascalCase | `CreatedAt`, `TotalAmount` |\n| Public methods | PascalCase | `CreateOrder`, `ValidatePayment` |\n| Private fields | `_camelCase` (underscore prefix) | `_repository`, `_logger` |\n| Constants | PascalCase | `DefaultTimeout`, `MaxRetryCount` |\n| Local variables | camelCase | `orderId`, `serializedData` |\n| Method parameters | camelCase | `cancellationToken`, `userId` |\n| Lambda parameters | Short camelCase | `x =>`, `e =>`, `o =>` |\n\n### 2.3 Async Methods\n\n> **All async methods MUST end with the `Async` suffix without exception.**\n\n```csharp\n\u002F\u002F ✅ Correct\npublic async Task\u003COrder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);\n\n\u002F\u002F ❌ Wrong – missing Async suffix\npublic async Task\u003COrder?> GetById(Guid id, CancellationToken cancellationToken);\n```\n\nThis applies to:\n- Interface declarations\n- Public and internal implementation methods\n- Private helper methods\n\n---\n\n## 3. Access Modifiers & Sealed Classes\n\n### 3.1 Least Privilege\n\n- Prefer `internal` for implementation types; use `public` only for types that are part of the public API surface.\n- Implementation classes registered via DI should be `internal sealed`.\n- Types that implement a public interface and form the public API are `public sealed`.\n\n```csharp\n\u002F\u002F ✅ Correct: public sealed for types exposed via public interface\npublic sealed class OrderService : IOrderService { }\n\n\u002F\u002F ✅ Correct: internal sealed for infrastructure implementations\ninternal sealed class SqlOrderRepository : IOrderRepository { }\n```\n\n### 3.2 `sealed` Usage\n\nMark classes `sealed` by default unless inheritance is explicitly required. This prevents unintended derivation and enables JIT optimizations.\n\n---\n\n## 4. Null Handling & Defensive Programming\n\n### 4.1 Nullable Reference Types\n\n- Enable nullable context for all projects (`\u003CNullable>enable\u003C\u002FNullable>`).\n- Annotate all nullable references explicitly with `?`.\n- Avoid the null-forgiving operator (`!`) without an inline comment explaining why it is safe.\n- Prefer early-return guards over deeply nested null checks.\n\n```csharp\n\u002F\u002F ✅ Early return guard\nif (id is null || id.Length == 0)\n{\n    return null;\n}\n```\n\n### 4.2 Argument Validation\n\nUse modern `ArgumentNullException` helpers for public\u002Finternal method boundaries:\n\n```csharp\n\u002F\u002F ✅ Correct\nArgumentNullException.ThrowIfNull(order);\nArgumentNullException.ThrowIfNullOrEmpty(order.UserName);\n```\n\n### 4.3 Null Propagation & Coalescing\n\nPrefer `?.` and `??` \u002F `??=` over verbose null checks in expressions:\n\n```csharp\n\u002F\u002F ✅ Correct\nreturn items?.Select(x => x.ToDto()).ToArray();\n\nvar name = input?.Trim() ?? string.Empty;\n```\n\n---\n\n## 5. Constructor Injection & Dependency Injection\n\n### 5.1 Constructor Injection\n\nAlways inject dependencies via the constructor. Store them as `private readonly` fields prefixed with `_`.\n\n```csharp\nprivate readonly IOrderRepository _orderRepository;\nprivate readonly ILogger\u003COrderService> _logger;\n\npublic OrderService(IOrderRepository orderRepository, ILogger\u003COrderService> logger)\n{\n    _orderRepository = orderRepository;\n    _logger = logger;\n}\n```\n\n### 5.2 Options Pattern\n\nAccess configuration via `IOptions\u003CT>`. Extract `.Value` in the constructor and store as a field – do not access `.Value` repeatedly at call sites.\n\n```csharp\nprivate readonly AppConfiguration _configuration;\n\npublic OrderService(IOptions\u003CAppConfiguration> options)\n{\n    _configuration = options.Value;\n}\n```\n\n### 5.3 DI Registration\n\nCentralize all service registrations in a dedicated `DependencyInjection.cs` static class with `IServiceCollection` extension methods.\n\n```csharp\npublic static class DependencyInjection\n{\n    public static void AddMyFeature(this IServiceCollection services, IConfiguration configuration)\n    {\n        services.AddTransient\u003CIOrderService, OrderService>();\n        services.AddKeyedTransient\u003CIPaymentStrategy, CreditCardStrategy>(\"creditcard\");\n    }\n}\n```\n\nLifetime guidance:\n- `AddTransient` – stateless, short-lived services.\n- `AddSingleton` – thread-safe, shared-state services (e.g., `TimeProvider`, static caches).\n- `AddKeyedTransient` \u002F `AddKeyedSingleton` – strategy-pattern registrations keyed by a discriminator.\n\n---\n\n## 6. Async \u002F Await\n\n### 6.1 Always Propagate CancellationToken\n\nEvery public and internal async method should accept a `CancellationToken` as its **last parameter**:\n\n```csharp\n\u002F\u002F ✅ Correct\nTask\u003COrder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);\nTask SaveAsync(Order order, CancellationToken cancellationToken);\n```\n\n### 6.2 No `ConfigureAwait(false)` in Application Code\n\nDo not use `.ConfigureAwait(false)` in application-layer and library code targeting ASP.NET Core. Reserve it only for low-level infrastructure libraries where synchronization context must be avoided explicitly.\n\n### 6.3 Never Use `async void`\n\nNever use `async void` except for event handlers. Always return `Task` or `Task\u003CT>`.\n\n### 6.4 Async Locks via SemaphoreSlim\n\nUse `SemaphoreSlim` for async-compatible critical sections. Always release in a `finally` block:\n\n```csharp\nprivate static readonly SemaphoreSlim Lock = new(1, 1);\n\nawait Lock.WaitAsync(cancellationToken);\ntry\n{\n    \u002F\u002F Critical section\n}\nfinally\n{\n    Lock.Release();\n}\n```\n\n### 6.5 Return Task Directly for Pass-Through Methods\n\nWhen a method only delegates to a single async call with no surrounding logic, return the `Task` directly to avoid an unnecessary state machine:\n\n```csharp\n\u002F\u002F ✅ Correct – no state machine overhead\nprivate Task\u003Cstring?> GetCachedValueAsync(string key, CancellationToken cancellationToken)\n{\n    return _cache.GetStringAsync(key, cancellationToken);\n}\n```\n\n---\n\n## 7. Result Pattern\n\n### 7.1 Internal Results\n\nDo not throw exceptions for expected, recoverable validation failures. Use typed result objects that carry success\u002Ffailure state and an optional message:\n\n```csharp\n\u002F\u002F Validator result (IsValid + Message)\npublic static ValidationResult Valid() => new(true);\npublic static ValidationResult Invalid(string message) => new(false, message);\n\n\u002F\u002F Handler\u002Foperation result (Value + HasError + Message)\npublic Result\u003CT> Execute(...)\n{\n    if (inputIsInvalid)\n        return new Result\u003CT>(\"Validation failed: input cannot be null\");\n\n    return new Result\u003CT>(computedValue);\n}\n```\n\n### 7.2 Public Results\n\nPublic-facing operation results use static factory methods for readability:\n\n```csharp\n\u002F\u002F ✅ Correct\nreturn OperationResult.Success();\nreturn OperationResult.Failure(\"The record was not found\");\n```\n\n### 7.3 Fail Fast, Return Early\n\nValidate all inputs at the top of the method. Return early on error. Do not let invalid state propagate deep into a method body.\n\n```csharp\nvar validation = _validator.Validate(request);\nif (!validation.IsValid)\n{\n    return OperationResult.Failure(validation.Message!);\n}\n\n\u002F\u002F proceed with valid data only\n```\n\n---\n\n## 8. Logging\n\n### 8.1 Structured Logging\n\nAlways use **named placeholder syntax** – never string interpolation in log messages:\n\n```csharp\n\u002F\u002F ✅ Correct\n_logger.LogWarning(\"Order '{OrderId}' was not found for user '{UserId}'\", orderId, userId);\n\n\u002F\u002F ❌ Wrong\n_logger.LogWarning($\"Order '{orderId}' was not found for user '{userId}'\");\n```\n\n### 8.2 Log Level Selection\n\n| Situation | Level |\n|---|---|\n| Normal successful operation | `LogDebug` |\n| Handled failure or unexpected but recoverable condition | `LogWarning` |\n| Unrecoverable exception or system error | `LogError` |\n| Sensitive \u002F PII data | Do not log – redact |\n\n### 8.3 Logger Injection\n\nAlways inject `ILogger\u003CT>` where `T` is the exact enclosing class. Do not share logger instances across types.\n\n---\n\n## 9. Collections & LINQ\n\n### 9.1 Collection Expressions\n\nUse C# 12+ collection expressions (`[]`) for empty collections and simple inline initialization:\n\n```csharp\n\u002F\u002F ✅ Correct\nstring[] tags = [];\nItems = existingItems ?? [],\nreturn [];\n```\n\n### 9.2 LINQ Style\n\n- Prefer **method syntax** over query syntax.\n- Chain transformations fluently (`.Where()`, `.Select()`, `.OrderBy()`) and materialize at the end with `.ToList()` or `.ToArray()`.\n- Avoid intermediate `.ToList()` calls mid-chain; defer materialization.\n\n```csharp\n\u002F\u002F ✅ Correct\nreturn orders\n    .Where(o => o.IsActive)\n    .Select(o => o.ToSummaryDto())\n    .ToArray();\n```\n\n### 9.3 Empty Collection Checks\n\nPrefer `.Length == 0` or `.Count == 0` over `!collection.Any()` in performance-sensitive paths.\n\n---\n\n## 10. Pattern Matching & Switch Expressions\n\nUse switch expressions for exhaustive value dispatch instead of chains of `if`\u002F`else if`:\n\n```csharp\n\u002F\u002F ✅ Correct\nvar label = status switch\n{\n    OrderStatus.Pending   => \"Awaiting confirmation\",\n    OrderStatus.Confirmed => \"Confirmed\",\n    OrderStatus.Shipped   => \"On the way\",\n    _                     => \"Unknown\",\n};\n```\n\nPrefer `is null` \u002F `is not null` over `== null` \u002F `!= null` for reference type null checks:\n\n```csharp\nif (order is null) { ... }\nif (result is not null) { ... }\n```\n\n---\n\n## 11. Domain Model Design\n\n### 11.1 Required Properties\n\nUse the `required` keyword for mandatory properties to enforce initialization at the call site:\n\n```csharp\npublic sealed class Order\n{\n    public required Guid Id { get; set; }\n    public required string CustomerName { get; set; }\n    public required decimal TotalAmount { get; set; }\n}\n```\n\n### 11.2 Sealed Domain Models\n\nSeal domain and result classes that are not designed for inheritance:\n\n```csharp\npublic sealed class Order { }\npublic sealed class OperationResult { }\n```\n\n---\n\n## 12. XML Documentation\n\n### 12.1 Public API\n\nAll `public` interfaces, classes, and their members must carry full XML doc comments:\n\n```csharp\n\u002F\u002F\u002F \u003Csummary>\n\u002F\u002F\u002F Retrieves an order by its unique identifier.\n\u002F\u002F\u002F \u003C\u002Fsummary>\n\u002F\u002F\u002F \u003Cparam name=\"id\">The unique identifier of the order.\u003C\u002Fparam>\n\u002F\u002F\u002F \u003Cparam name=\"cancellationToken\">A cancellation token.\u003C\u002Fparam>\n\u002F\u002F\u002F \u003Creturns>The order if found; otherwise, \u003Cc>null\u003C\u002Fc>.\u003C\u002Freturns>\nTask\u003COrder?> GetByIdAsync(Guid id, CancellationToken cancellationToken);\n```\n\n### 12.2 Internal Types\n\nXML doc comments are optional on `internal` types but strongly encouraged for any non-trivial logic.\n\n---\n\n## 13. Constants & Magic Values\n\n### 13.1 Named Constants\n\nNever use magic numbers or strings inline. Declare them as `private const` or `private static readonly`:\n\n```csharp\nprivate const int MaxRetryCount = 3;\nprivate const string DefaultCacheKeyPrefix = \"order\";\nprivate const int DefaultTimeoutSeconds = 60;\n```\n\n### 13.2 Constants Organization\n\nGroup related constants into dedicated static classes inside a `Constants\u002F` folder. One class per logical domain (e.g., `CacheKeys`, `HeaderNames`, `ErrorMessages`).\n\n---\n\n## 14. Formatting\n\n### 14.1 Indentation & Whitespace\n\n- **Indent size**: 4 spaces – no tabs.\n- **Line endings**: CRLF.\n- One blank line between method bodies.\n- One blank line between property groups.\n\n### 14.2 Braces\n\nAlways use braces, even for single-line `if` \u002F `else` \u002F `for` \u002F `foreach` bodies:\n\n```csharp\n\u002F\u002F ✅ Correct\nif (order is null)\n{\n    return OperationResult.Failure(\"Order not found\");\n}\n\n\u002F\u002F ❌ Wrong\nif (order is null)\n    return OperationResult.Failure(\"Order not found\");\n```\n\n### 14.3 Expression-Bodied Members\n\n| Member Type | Preferred Style |\n|---|---|\n| Properties | Expression-bodied (`=>`) allowed |\n| Short indexers | Expression-bodied allowed |\n| Methods | **Block body** preferred |\n| Constructors | **Block body** required |\n| Lambdas | Expression-bodied preferred |\n| Local functions | Block body preferred |\n\n### 14.4 Long Parameter Lists\n\nBreak constructor or method parameters onto separate lines when there are 3 or more:\n\n```csharp\npublic OrderService(\n    IOrderRepository orderRepository,\n    IPaymentService paymentService,\n    IOptions\u003CAppConfiguration> options,\n    ILogger\u003COrderService> logger)\n```\n\n### 14.5 Object & Collection Initializers\n\nAlways use object initializer syntax for domain objects and DTOs. Include a trailing comma after the last member:\n\n```csharp\nvar order = new Order\n{\n    Id = Guid.NewGuid(),\n    CustomerName = request.CustomerName.Trim(),\n    TotalAmount = request.Amount,\n    Tags = [],\n};\n```\n\n---\n\n## 15. Extension Methods\n\n- Place extension methods in a dedicated `Extensions\u002F` folder.\n- One static class per extended type or logical concept: `StringExtensions`, `EnumExtensions`, `DateTimeExtensions`.\n- All extension classes are `public static`.\n- Generic constraints should be as tight as the use case requires.\n\n```csharp\npublic static class EnumExtensions\n{\n    public static string GetSerializedValue\u003CT>(this T value) where T : Enum { ... }\n    public static T ToEnum\u003CT>(this string value) where T : struct, Enum { ... }\n    public static T? ToNullableEnum\u003CT>(this string? value) where T : struct, Enum { ... }\n}\n```\n\n---\n\n## 16. Security-Sensitive Code\n\n- Never log raw sensitive bytes, private key material, passwords, tokens, or PII.\n- Use constant-time or span-based byte array comparison helpers to prevent timing attacks – never use `==` or `SequenceEqual` for security-critical comparisons.\n- Always sanitize user input (`.Trim()`) before storing, comparing, or forwarding.\n- Validate all untrusted input at the boundary layer – do not rely on inner layers to catch invalid data.\n\n---\n\n## Quick Reference Checklist\n\nBefore submitting any C# file, verify:\n\n- [ ] File-scoped namespace used\n- [ ] All async methods end with the `Async` suffix\n- [ ] `CancellationToken` is the last parameter of every async method\n- [ ] Nullable reference types annotated correctly – no unexplained `!`\n- [ ] Braces on every `if` \u002F `else` \u002F `for` \u002F `foreach`\n- [ ] No magic numbers or strings – all constants named\n- [ ] Structured logging – no string interpolation in log calls\n- [ ] Public API members have XML documentation\n- [ ] Result pattern used instead of exceptions for expected failures\n",{"name":5,"description":7},"main","d9396b885cd7f0f2db22f78208565be82ba0d0b1",".gemini\u002Fskills\u002Fcsharp-coding-standards",0,"https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook","https:\u002F\u002Fgithub.com\u002Flinuxchata","https:\u002F\u002Fshark-fido2.com","Improving a WebAuthn library for stronger, passwordless authentication","2026-05-15 14:54:09",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add linuxchata\u002Fai-playbook --skill csharp-coding-standards",{"tool":59,"command":60},"bunx","bunx skills add linuxchata\u002Fai-playbook --skill csharp-coding-standards",{"tool":62,"command":63},"pnpm","pnpm dlx skills add linuxchata\u002Fai-playbook --skill csharp-coding-standards","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002F.gemini\u002Fskills\u002Fcsharp-coding-standards\u002FSKILL.md",true,[],[68,76,85,103,119,124],{"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":39},"01M70FMR99EKK910WZNEA5Y3FC","{name=null}","{description=null}","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002Ftemplates\u002F.gemini\u002FSKILL.md",[],[70,75],"name",{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":39},"01M70FMNCNTWPW39VHVKKH2Y2V","[name]","[description]","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002Ftemplates\u002F.claude\u002FSKILL.md",[],[75,78,83,84],"version","metadata",{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":39},"01M70FMJCKA1E80083CV8KYRQ5","csharp-testing-standards","Defines the testing standards, patterns, and conventions for all C# unit and integration test projects. Rules cover test framework usage, naming, structure, mocking, assertions, and parameterization. Apply these rules uniformly across all test projects.","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002F.gemini\u002Fskills\u002Fcsharp-testing-standards\u002FSKILL.md",[],[92,93,94,19,21,95,31,96,38,37,28,27,97,98,99,100,101,102,35,34],"testing","testing standards","csharp testing","csharp testing standards","unit","framework","usage","for","integration test","mocking","assertions",{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":39},"01M70FMBREZHWVGG3HNSZ9WJ9Q","csharp-api-controller-standards","Defines the coding standards, patterns, and conventions for ASP.NET Core REST API controllers. Rules cover routing, HTTP verbs, response types, XML documentation, dependency injection, and asynchronous execution. Apply these rules uniformly to ensure a consistent, predictable, and well-documented API surface.","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002F.gemini\u002Fskills\u002Fcsharp-api-controller-standards\u002FSKILL.md",[],[110,111,19,112,21,23,113,99,114,115,35,24,116,117,118,29,20,28,36,27],"api","controller","csharp api controller standards","core","execution","http","types","asynchronous","documentation",{"skillNo":120,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":39},"01M70FM8TDR0AMB13QY51PWPJH","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fcsharp-testing-standards\u002FSKILL.md",[],[93,94,19,21,95,92,102,96,38,31,37,28,27,97,98,99,100,101,35,34],{"skillNo":125,"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":126,"categories":127,"keywords":128,"publishedAt":39},"01M70FM5038ENYXF2RSB4CKDH0","https:\u002F\u002Fgithub.com\u002Flinuxchata\u002Fai-playbook\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fcsharp-coding-standards\u002FSKILL.md",[],[20,23,22,21,19,29,30,37,31,32,38,34,35,129,24,25,26,27,36,28],"async"]