[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75VE19HNCM10JTTH11J9FGT":3,"skill-same:01M75VE19HNCM10JTTH11J9FGT":52},{"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":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M75VE19HNCM10JTTH11J9FGT","csharp-coding-style",null,"Use when writing, reviewing, or changing C#\u002F.NET code in this repo, especially packages\u002Fsource-windows Core, Helper, ControlPanel, .csproj, .editorconfig, NativeAOT, nullable, async\u002Fthreading, and modern C# feature decisions. Pair with coding-style for language-neutral naming, comments, tests, and ownership rules.","ShoMetrics\u002Fsho_metrics","ShoMetrics","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F286841904?v=4","01M75VDM9S89QVZQZG8P589MVS","Sho Metrics","01M75VDMAE77E47W94V8P60S84",21,"GPL-3.0","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fcsharp-coding-style\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: csharp-coding-style\ndescription: Use when writing, reviewing, or changing C#\u002F.NET code in this repo, especially packages\u002Fsource-windows Core, Helper, ControlPanel, .csproj, .editorconfig, NativeAOT, nullable, async\u002Fthreading, and modern C# feature decisions. Pair with coding-style for language-neutral naming, comments, tests, and ownership rules.\n---\n\n# C# Coding Style\n\nUse this skill for C#\u002F.NET-specific decisions. Use `coding-style` for language-neutral naming, comments, tests, and ownership rules.\n\nBaseline: follow dotnet\u002Fruntime C# style unless this repo overrides it. Use Microsoft Learn C# conventions where runtime style is silent. Prefer `.editorconfig` and built-in analyzers over prose-only rules.\n\nRules here are defaults, not blind transformations. If generated code, WinUI\u002FXAML requirements, dependency APIs, NativeAOT limitations, or a file's clear local style conflicts with a rule, preserve correctness and state the reason. Where examples use `Too rigid`, that means mechanically following the rule would make the code worse.\n\n## 1. Project Defaults\n\n* **PREFER: Target .NET 10 and C# 14 for new Windows source projects** unless a dependency, packaging, or Windows SDK constraint requires otherwise.\n  - Good: `\u003CTargetFramework>net10.0-windows\u003C\u002FTargetFramework>`\n  - Bad: `\u003CTargetFramework>netstandard2.0\u003C\u002FTargetFramework>` for the Windows hardware source.\n  - Too rigid: using `net10.0-windows10.0.19041.0` in `Helper` just because `ControlPanel` needs WinUI\u002FWindows SDK APIs.\n\n* **DO: Enable nullable reference types**. Treat non-nullable references as the default. Use `?` only when null is a real domain state or boundary result.\n  - Good: `public string? ParentSensorId { get; init; }`\n  - Bad: `public string SensorId { get; init; } = null!;`\n  - Too rigid: `public string ParentSensorId { get; init; } = \"\";` when \"no parent sensor\" is a real state.\n\n* **PREFER: Keep `Core` free of UI, CLI, and Node IPC concerns**. LHM\u002FPawnIO access, sensor cataloging, and metric mapping belong in `Core`; `Helper` and `ControlPanel` consume `Core`.\n  - Good: `Core` returns `IReadOnlyList\u003CSensorSnapshot>`.\n  - Bad: `Core` references `Microsoft.UI.Xaml` or writes to `Console.Out`.\n  - Too rigid: moving `SensorSnapshot` out of `Core` only because `Helper` later serializes it.\n\n## 2. Types And Construction\n\n* **PREFER: Make internal and private classes `sealed` by default**. Leave a type unsealed for a real inheritance, framework, proxy, or test-substitution need.\n  - Good: `internal sealed class LibreHardwareReader`\n  - Bad: `internal class SensorMapper` with no subclassing requirement.\n  - Too rigid: `public sealed class HardwareSource` when `LibreHardwareSource : HardwareSource` is the intended extension point.\n\n* **PREFER: Use `required` plus `init` for object-initialized DTOs and options**. Use constructors or factories when invariants span multiple values or construction has behavior.\n  - Good: `public required string Identifier { get; init; }`\n  - Bad: `public string Identifier { get; set; } = \"\";` on an immutable snapshot DTO.\n  - Too rigid: `public required double Minimum { get; init; } public required double Maximum { get; init; }` when a constructor must validate `minimum \u003C= maximum`.\n\n* **PREFER: Use records only for immutable values and results**. Avoid records for hardware owners, long-lived runtime state, mutable caches, and types where `with` copying hides cost or ownership.\n  - Good: `public readonly record struct SensorKey(string HardwareId, string SensorId);`\n  - Bad: `public record HardwareMonitorSession(Computer Computer);`\n  - Too rigid: replacing every immutable result with `record` when it owns large mutable arrays or disposable handles.\n\n* **PREFER: Use primary constructors for small sealed types or records when parameters only initialize fields\u002Fproperties or pass to `base`**. In larger types, assign constructor parameters to explicitly named `_camelCase` fields so ownership stays visible.\n  - Good: `public readonly record struct SensorReading(string SensorId, double Value);`\n  - Bad: `public readonly record struct SensorReading { public SensorReading(string sensorId, double value) { SensorId = sensorId; Value = value; } public string SensorId { get; } public double Value { get; } }`\n  - Too rigid: `internal sealed class ControlPanelViewModel(IHardwareReader reader, ISettingsStore settingsStore, ILogger logger, IDispatcher dispatcher, IFilePicker filePicker) { }`\n\n* **CONSIDER: Use the C# 14 `field` keyword only for local property validation**. Use an explicit backing field when the state needs a domain name, debugging clarity, or multi-accessor behavior.\n  - Good: `public int PollingIntervalSeconds { get; set => field = value > 0 ? value : throw new ArgumentOutOfRangeException(nameof(value)); }`\n  - Bad: `private int _pollingIntervalSeconds; public int PollingIntervalSeconds { get => _pollingIntervalSeconds; set => _pollingIntervalSeconds = value > 0 ? value : throw new ArgumentOutOfRangeException(nameof(value)); }`\n  - Too rigid: `set => field = NormalizePollingInterval(value);` when several other members also need the normalized value.\n\n## 3. NativeAOT And Trimming\n\n* **DO: Treat NativeAOT and trimming warnings as design-affecting**. Fix them at the boundary, or annotate the narrow incompatible member with `RequiresDynamicCode`, `RequiresUnreferencedCode`, or `DynamicDependency` and explain why it remains.\n  - Good: `[JsonSerializable(typeof(SensorSnapshot))] internal partial class SourceJsonContext : JsonSerializerContext`\n  - Bad: `\u003CNoWarn>IL2026;IL3050\u003C\u002FNoWarn>` to silence the whole project.\n  - Too rigid: rejecting LHM integration because one adapter method needs `[RequiresUnreferencedCode(\"LibreHardwareMonitor reflection usage is isolated here.\")]`.\n\n* **AVOID: Runtime type construction or reflection dispatch in production paths**. Use it only when isolated, annotated, and tested under NativeAOT publish.\n  - Good: `private static readonly Dictionary\u003Cstring, Func\u003CIMetricReader>> ReaderFactories = ...;`\n  - Bad: `Activator.CreateInstance(typeNameFromSettings)`\n  - Too rigid: replacing `typeof(SensorSnapshot).Name` because all `typeof(...)` usage was mistaken for reflection dispatch.\n\n* **PREFER: Use explicit factories, interface dispatch, source generators, and `System.Text.Json` source generation** instead of reflection-heavy discovery.\n  - Good: `JsonSerializer.Serialize(snapshot, SourceJsonContext.Default.SensorSnapshot)`\n  - Bad: `JsonSerializer.Serialize(snapshot)` in a NativeAOT-published helper.\n  - Too rigid: adding a source generator for test-only JSON fixtures that are not published with NativeAOT.\n\n* **AVOID: `TypeDescriptor`, `DataContractSerializer`, `BinaryFormatter`, `Reflection.Emit`, and dynamic assembly loading** in Windows source projects.\n  - Good: `JsonSerializer.Deserialize(json, SourceJsonContext.Default.SensorSnapshot)`\n  - Bad: `new DataContractSerializer(typeof(SensorSnapshot))`\n  - Too rigid: deleting `LibreHardwareMonitor.Hardware.Computer` usage solely because the package may use reflection internally; isolate the adapter instead.\n\n* **PREFER: Use source-generated interop for NativeAOT boundaries**. Use `LibraryImport` for new P\u002FInvoke and CsWinRT or source-generated `ComWrappers` for COM\u002FWinRT instead of built-in COM interop.\n  - Good: `[LibraryImport(\"kernel32\", SetLastError = true)] private static partial nint GetCurrentProcess();`\n  - Bad: `[ComImport] interface IWmiLocator { ... }` in a NativeAOT-published helper.\n  - Too rigid: rewriting a dependency-owned interop layer that is already isolated and tested under NativeAOT.\n\n* **CONSIDER: Use `UnsafeAccessor` only at a narrow interop or test boundary** when an explicit API, factory, or source generator cannot express the required access.\n  - Good: `[UnsafeAccessor(UnsafeAccessorKind.Method, Name = \"ReadMsr\")] private static extern int ReadMsr(Cpu cpu);`\n  - Bad: `[UnsafeAccessor(UnsafeAccessorKind.Field, Name = \"_cache\")] private static extern ref Dictionary\u003Cstring, object> Cache(object owner);`\n  - Too rigid: adding `public int ReadMsrForTests()` to production APIs only to avoid a test-boundary `UnsafeAccessor`.\n\n## 4. Async And Threading\n\n* **DO: Accept `CancellationToken` as the last parameter on public or internal async, polling, blocking, or I\u002FO methods when the caller can control lifetime**. Do not make it optional on Core\u002FHelper APIs that participate in shutdown.\n  - Good: `Task\u003CIReadOnlyList\u003CSensorSnapshot>> ReadAsync(CancellationToken cancellationToken)`\n  - Bad: `Task PollAsync()` for a long-running polling loop.\n  - Too rigid: `double NormalizePercentage(double value, CancellationToken cancellationToken)` for pure CPU math.\n\n* **DO: Use `ConfigureAwait(false)` in Core and Helper library code**. Do not use it in WinUI code that must resume on the UI thread.\n  - Good: `await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);`\n  - Bad: `await process.WaitForExitAsync(cancellationToken);` in Core\u002FHelper library code.\n  - Too rigid: `await RefreshUiAsync().ConfigureAwait(false); statusText.Text = \"Ready\";`\n\n* **DON'T: Use `async void` except for event handlers**. Event handlers must catch and report exceptions at the UI or process boundary.\n  - Good: `private async void OnRefreshClicked(object sender, RoutedEventArgs args) { try { await RefreshAsync(); } catch (Exception exception) { ReportError(exception); } }`\n  - Bad: `public async void PollAsync()`\n  - Too rigid: refusing `async void` for a WinUI event handler and inventing awkward sync wrappers.\n\n* **DON'T: Block on async work with `.Result`, `.Wait()`, or `.GetAwaiter().GetResult()`** except at an explicit synchronous process boundary with a documented reason.\n  - Good: `await RunAsync(cancellationToken).ConfigureAwait(false);`\n  - Bad: `ReadAsync(cancellationToken).Result`\n  - Too rigid: rewriting a required synchronous host entry point instead of using `RunAsync(cancellationToken).GetAwaiter().GetResult(); \u002F\u002F Host requires sync entry.`\n\n* **PREFER: Return `Task` or `Task\u003CT>` by default**. Use `ValueTask\u003CT>` only for measured hot paths or APIs that usually complete synchronously and have clear single-consumption semantics.\n  - Good: `Task\u003CSensorSnapshot> ReadAsync(CancellationToken cancellationToken)`\n  - Bad: storing `ValueTask\u003CSensorSnapshot>` in a field, returning it to multiple consumers, or awaiting it twice.\n  - Too rigid: refusing `ValueTask\u003CT>` for a measured hot-path cache lookup that usually completes synchronously.\n\n* **PREFER: Use a dedicated `System.Threading.Lock` for synchronous private locks in .NET 9+ \u002F C# 13+ code**. Use async-compatible coordination, such as `SemaphoreSlim`, when the protected operation awaits.\n  - Good: `private readonly Lock _gate = new();`\n  - Bad: `private readonly object _lock = new();` in new .NET 9+ \u002F C# 13+ code without a compatibility reason.\n  - Too rigid: using `lock (_gate) { await RefreshAsync(); }` instead of `SemaphoreSlim`.\n\n* **PREFER: Match disposal syntax to the resource and scope**. Use `await using` whenever the type implements `IAsyncDisposable`, even if it also implements `IDisposable`; the synchronous path may skip async cleanup. Use `using var` when the enclosing block is the intended synchronous lifetime; use a `using (...)` statement when early disposal matters.\n  - Good: `await using HardwareMonitorSession session = await HardwareMonitorSession.OpenAsync(cancellationToken);`\n  - Bad: `using HardwareMonitorSession session = await HardwareMonitorSession.OpenAsync(cancellationToken);` when the session implements `IAsyncDisposable`.\n  - Bad: `using var session = new HardwareMonitorSession();` inside an async method when `HardwareMonitorSession` implements `IAsyncDisposable`.\n  - Too rigid: wrapping every disposable in `using (...) { }` even when method-scope `using var` is clearer and equivalent.\n\n* **CONSIDER: Use `IAsyncEnumerable\u003CT>` for real streams**. Keep one-shot snapshots as `Task\u003CIReadOnlyList\u003CT>>`.\n  - Good: `await foreach (SensorSnapshot snapshot in session.ReadSnapshotsAsync(cancellationToken)) { ... }`\n  - Bad: repeatedly returning growing `Task\u003CIReadOnlyList\u003CSensorSnapshot>>` batches for an unbounded polling stream.\n  - Too rigid: exposing `IAsyncEnumerable\u003CT>` for a single hardware snapshot request.\n\n## 5. Span And Ref Safety\n\n* **PREFER: Use `ReadOnlySpan\u003CT>` or `Span\u003CT>` for hot in-process parsing and formatting helpers**. Keep spans, `ref struct`, and `scoped` values out of JSON, IPC, UI, and long-lived domain contracts unless profiling or interop requires them.\n  - Good: `static bool TryParseSensorPath(ReadOnlySpan\u003Cchar> path, out SensorPath result)`\n  - Bad: `public ReadOnlySpan\u003Cchar> SensorPath { get; init; }` on a JSON DTO.\n  - Too rigid: changing `public required string SensorPath { get; init; }` to span-based DTO plumbing for theoretical performance.\n\n* **CONSIDER: Use `params ReadOnlySpan\u003CT>` only for low-level helpers where caller convenience avoids repeated array allocations**.\n  - Good: `static bool IsAny(SensorType value, params ReadOnlySpan\u003CSensorType> allowed)`\n  - Bad: `public SensorQuery Include(params ReadOnlySpan\u003CSensorType> sensorTypes)` on a durable public domain API.\n  - Too rigid: keeping `static bool IsAny(SensorType value, params SensorType[] allowed)` in a measured hot helper.\n\n* **CONSIDER: Use `allows ref struct` only in generic helpers that already operate on spans or other `ref struct` values**. Keep it out of ordinary domain APIs.\n  - Good: `static bool TryRead\u003CTReader>(scoped ref TReader reader) where TReader : allows ref struct`\n  - Bad: `MetricRepository\u003CT> where T : allows ref struct`\n  - Too rigid: duplicating parser helpers for each span-backed reader only to avoid `allows ref struct`.\n\n## 6. Local C# Syntax\n\n* **PREFER: Use modern argument guards and pattern null checks**. Use `ThrowIf...` helpers for ordinary parameter validation, and `is null` \u002F `is not null` for explicit null tests.\n  - Good: `ArgumentNullException.ThrowIfNull(snapshot);`\n  - Good: `if (snapshot is null) return;`\n  - Bad: `if (snapshot == null) throw new ArgumentNullException(nameof(snapshot));`\n  - Too rigid: replacing a domain-specific validation error with `ArgumentNullException.ThrowIfNull(...)`.\n\n* **DO: Follow the dotnet\u002Fruntime `var` rule**: use `var` only when the type is explicitly named on the right-hand side, typically `new` or an explicit cast. Do not use `var` for method return values, LINQ results, or built-in scalar literals.\n  - Good: `var reader = new LibreHardwareReader();`\n  - Bad: `var snapshot = reader.Read();`\n  - Bad: `var retryLimit = 3;`\n\n* **PREFER: Use target-typed `new()` only when the left-hand side explicitly names the type**.\n  - Good: `List\u003CSensorSnapshot> snapshots = new();`\n  - Bad: `List\u003CSensorSnapshot> snapshots = new List\u003CSensorSnapshot>();`\n\n* **PREFER: Use collection expressions for target-typed arrays, lists, and spans**. Avoid them when the target type is not obvious or allocation behavior matters to the code being reviewed.\n  - Good: `SensorType[] supportedTypes = [SensorType.Load, SensorType.Temperature];`\n  - Bad: `var supportedTypes = [SensorType.Load, SensorType.Temperature];`\n  - Too rigid: replacing `ImmutableArray\u003CSensorType>.Empty` with `[]` without checking the target type and allocation semantics.\n\n* **PREFER: Use LINQ method chains, not query syntax**.\n  - Good: `sensors.Where(sensor => sensor.Type == SensorType.Temperature).Select(sensor => sensor.Value)`\n  - Bad: `from sensor in sensors where sensor.Type == SensorType.Temperature select sensor.Value`\n\n* **PREFER: Use pattern matching for simple null\u002Ftype\u002Fenum dispatch**. Use `switch` expressions for value-producing dispatch; keep `switch` statements or `if` chains when side-effect order is clearer.\n  - Good: `return sensor.Type switch { SensorType.Load => \"load\", SensorType.Temperature => \"temp\", _ => \"unknown\" };`\n  - Good: `if (value is SensorSnapshot snapshot) { ... }`\n  - Bad: `SensorSnapshot? snapshot = value as SensorSnapshot; if (snapshot is not null) { ... }`\n  - Too rigid: forcing a large side-effecting workflow into a `switch` expression.\n\n* **DO: Use PascalCase for C# constants** except interop constants that intentionally mirror an external API name.\n  - Good: `private const int DefaultPollingIntervalSeconds = 1;`\n  - Bad: `private const int DEFAULT_POLLING_INTERVAL_SECONDS = 1;`\n  - Too rigid: renaming `WM_DEVICECHANGE` when intentionally mirroring Win32.\n\n* **DO: Use `nameof(...)` for strings that refer to C# members, parameters, or properties**.\n  - Good: `throw new ArgumentOutOfRangeException(nameof(pollingIntervalSeconds));`\n  - Bad: `throw new ArgumentOutOfRangeException(\"pollingIntervalSeconds\");`\n\n* **PREFER: Keep global usings limited to namespaces that are truly universal for the project**. Do not add a global using to save one local `using`.\n  - Good: `using LibreHardwareMonitor.Hardware;` only in the LHM adapter file.\n  - Bad: `global using LibreHardwareMonitor.Hardware;` for one adapter.\n  - Too rigid: banning `global using System;` in a project that consistently uses implicit\u002Fglobal base usings.\n\n## 7. Organization And Caller Readability\n\n* **PREFER: Order class members consistently**: nested types\u002Fevents, static\u002Fconst\u002Freadonly fields, instance fields\u002Fproperties, constructors, methods. Within a group, prefer `public`, `internal`, `protected`, then `private`; keep related interface implementation members together without adding `#region` unless the file already uses regions.\n  - Good: constants and fields before constructors; public API before private helpers in the same member group.\n  - Bad: private helpers before fields, constructor between unrelated methods, and interface members scattered through the class.\n  - Too rigid: moving a private helper far away from the only method that uses it when local readability is better.\n\n* **DO: Keep call sites self-explanatory when arguments are non-obvious**. Use named arguments for boolean\u002Fnull literals, named constants for repeated literals, and local variables for complex expressions.\n  - Good: `service.Start(useSsl: true);`\n  - Good: `TimeSpan timeout = TimeSpan.FromSeconds(5); client.Connect(endpoint, timeout);`\n  - Bad: `service.Start(true);`\n  - Bad: `client.Connect(endpoint, TimeSpan.FromMilliseconds(Math.Max(100, retryCount * 250)));`\n\n* **PREFER: Use the narrowest truthful collection type at API boundaries**. Inputs should not require `List\u003CT>` unless the method needs list-specific mutation or indexing. Outputs should communicate ownership: `IReadOnlyList\u003CT>` for snapshots, `List\u003CT>` when transferring a mutable container, arrays for fixed-size buffers or constants.\n  - Good: `void Publish(IReadOnlyList\u003CSensorSnapshot> snapshots)`\n  - Bad: `void Publish(List\u003CSensorSnapshot> snapshots)` when the method only enumerates.\n  - Too rigid: `IEnumerable\u003CSensorSnapshot>` when the method indexes or enumerates the sequence multiple times.\n\n* **DO: Use formatter-stable C# layout**. Use 4-space indentation, braces on control statements, one statement per line, and one blank line between members. Prefer the repo's `.editorconfig` if one is added later.\n  - Good: `if (isReady) { ... }` with braces before formatting expands it.\n  - Bad: `if (isReady) Start();`\n","# C# Coding Style\n\nUse this skill for C#\u002F.NET-specific decisions. Use `coding-style` for language-neutral naming, comments, tests, and ownership rules.\n\nBaseline: follow dotnet\u002Fruntime C# style unless this repo overrides it. Use Microsoft Learn C# conventions where runtime style is silent. Prefer `.editorconfig` and built-in analyzers over prose-only rules.\n\nRules here are defaults, not blind transformations. If generated code, WinUI\u002FXAML requirements, dependency APIs, NativeAOT limitations, or a file's clear local style conflicts with a rule, preserve correctness and state the reason. Where examples use `Too rigid`, that means mechanically following the rule would make the code worse.\n\n## 1. Project Defaults\n\n* **PREFER: Target .NET 10 and C# 14 for new Windows source projects** unless a dependency, packaging, or Windows SDK constraint requires otherwise.\n  - Good: `\u003CTargetFramework>net10.0-windows\u003C\u002FTargetFramework>`\n  - Bad: `\u003CTargetFramework>netstandard2.0\u003C\u002FTargetFramework>` for the Windows hardware source.\n  - Too rigid: using `net10.0-windows10.0.19041.0` in `Helper` just because `ControlPanel` needs WinUI\u002FWindows SDK APIs.\n\n* **DO: Enable nullable reference types**. Treat non-nullable references as the default. Use `?` only when null is a real domain state or boundary result.\n  - Good: `public string? ParentSensorId { get; init; }`\n  - Bad: `public string SensorId { get; init; } = null!;`\n  - Too rigid: `public string ParentSensorId { get; init; } = \"\";` when \"no parent sensor\" is a real state.\n\n* **PREFER: Keep `Core` free of UI, CLI, and Node IPC concerns**. LHM\u002FPawnIO access, sensor cataloging, and metric mapping belong in `Core`; `Helper` and `ControlPanel` consume `Core`.\n  - Good: `Core` returns `IReadOnlyList\u003CSensorSnapshot>`.\n  - Bad: `Core` references `Microsoft.UI.Xaml` or writes to `Console.Out`.\n  - Too rigid: moving `SensorSnapshot` out of `Core` only because `Helper` later serializes it.\n\n## 2. Types And Construction\n\n* **PREFER: Make internal and private classes `sealed` by default**. Leave a type unsealed for a real inheritance, framework, proxy, or test-substitution need.\n  - Good: `internal sealed class LibreHardwareReader`\n  - Bad: `internal class SensorMapper` with no subclassing requirement.\n  - Too rigid: `public sealed class HardwareSource` when `LibreHardwareSource : HardwareSource` is the intended extension point.\n\n* **PREFER: Use `required` plus `init` for object-initialized DTOs and options**. Use constructors or factories when invariants span multiple values or construction has behavior.\n  - Good: `public required string Identifier { get; init; }`\n  - Bad: `public string Identifier { get; set; } = \"\";` on an immutable snapshot DTO.\n  - Too rigid: `public required double Minimum { get; init; } public required double Maximum { get; init; }` when a constructor must validate `minimum \u003C= maximum`.\n\n* **PREFER: Use records only for immutable values and results**. Avoid records for hardware owners, long-lived runtime state, mutable caches, and types where `with` copying hides cost or ownership.\n  - Good: `public readonly record struct SensorKey(string HardwareId, string SensorId);`\n  - Bad: `public record HardwareMonitorSession(Computer Computer);`\n  - Too rigid: replacing every immutable result with `record` when it owns large mutable arrays or disposable handles.\n\n* **PREFER: Use primary constructors for small sealed types or records when parameters only initialize fields\u002Fproperties or pass to `base`**. In larger types, assign constructor parameters to explicitly named `_camelCase` fields so ownership stays visible.\n  - Good: `public readonly record struct SensorReading(string SensorId, double Value);`\n  - Bad: `public readonly record struct SensorReading { public SensorReading(string sensorId, double value) { SensorId = sensorId; Value = value; } public string SensorId { get; } public double Value { get; } }`\n  - Too rigid: `internal sealed class ControlPanelViewModel(IHardwareReader reader, ISettingsStore settingsStore, ILogger logger, IDispatcher dispatcher, IFilePicker filePicker) { }`\n\n* **CONSIDER: Use the C# 14 `field` keyword only for local property validation**. Use an explicit backing field when the state needs a domain name, debugging clarity, or multi-accessor behavior.\n  - Good: `public int PollingIntervalSeconds { get; set => field = value > 0 ? value : throw new ArgumentOutOfRangeException(nameof(value)); }`\n  - Bad: `private int _pollingIntervalSeconds; public int PollingIntervalSeconds { get => _pollingIntervalSeconds; set => _pollingIntervalSeconds = value > 0 ? value : throw new ArgumentOutOfRangeException(nameof(value)); }`\n  - Too rigid: `set => field = NormalizePollingInterval(value);` when several other members also need the normalized value.\n\n## 3. NativeAOT And Trimming\n\n* **DO: Treat NativeAOT and trimming warnings as design-affecting**. Fix them at the boundary, or annotate the narrow incompatible member with `RequiresDynamicCode`, `RequiresUnreferencedCode`, or `DynamicDependency` and explain why it remains.\n  - Good: `[JsonSerializable(typeof(SensorSnapshot))] internal partial class SourceJsonContext : JsonSerializerContext`\n  - Bad: `\u003CNoWarn>IL2026;IL3050\u003C\u002FNoWarn>` to silence the whole project.\n  - Too rigid: rejecting LHM integration because one adapter method needs `[RequiresUnreferencedCode(\"LibreHardwareMonitor reflection usage is isolated here.\")]`.\n\n* **AVOID: Runtime type construction or reflection dispatch in production paths**. Use it only when isolated, annotated, and tested under NativeAOT publish.\n  - Good: `private static readonly Dictionary\u003Cstring, Func\u003CIMetricReader>> ReaderFactories = ...;`\n  - Bad: `Activator.CreateInstance(typeNameFromSettings)`\n  - Too rigid: replacing `typeof(SensorSnapshot).Name` because all `typeof(...)` usage was mistaken for reflection dispatch.\n\n* **PREFER: Use explicit factories, interface dispatch, source generators, and `System.Text.Json` source generation** instead of reflection-heavy discovery.\n  - Good: `JsonSerializer.Serialize(snapshot, SourceJsonContext.Default.SensorSnapshot)`\n  - Bad: `JsonSerializer.Serialize(snapshot)` in a NativeAOT-published helper.\n  - Too rigid: adding a source generator for test-only JSON fixtures that are not published with NativeAOT.\n\n* **AVOID: `TypeDescriptor`, `DataContractSerializer`, `BinaryFormatter`, `Reflection.Emit`, and dynamic assembly loading** in Windows source projects.\n  - Good: `JsonSerializer.Deserialize(json, SourceJsonContext.Default.SensorSnapshot)`\n  - Bad: `new DataContractSerializer(typeof(SensorSnapshot))`\n  - Too rigid: deleting `LibreHardwareMonitor.Hardware.Computer` usage solely because the package may use reflection internally; isolate the adapter instead.\n\n* **PREFER: Use source-generated interop for NativeAOT boundaries**. Use `LibraryImport` for new P\u002FInvoke and CsWinRT or source-generated `ComWrappers` for COM\u002FWinRT instead of built-in COM interop.\n  - Good: `[LibraryImport(\"kernel32\", SetLastError = true)] private static partial nint GetCurrentProcess();`\n  - Bad: `[ComImport] interface IWmiLocator { ... }` in a NativeAOT-published helper.\n  - Too rigid: rewriting a dependency-owned interop layer that is already isolated and tested under NativeAOT.\n\n* **CONSIDER: Use `UnsafeAccessor` only at a narrow interop or test boundary** when an explicit API, factory, or source generator cannot express the required access.\n  - Good: `[UnsafeAccessor(UnsafeAccessorKind.Method, Name = \"ReadMsr\")] private static extern int ReadMsr(Cpu cpu);`\n  - Bad: `[UnsafeAccessor(UnsafeAccessorKind.Field, Name = \"_cache\")] private static extern ref Dictionary\u003Cstring, object> Cache(object owner);`\n  - Too rigid: adding `public int ReadMsrForTests()` to production APIs only to avoid a test-boundary `UnsafeAccessor`.\n\n## 4. Async And Threading\n\n* **DO: Accept `CancellationToken` as the last parameter on public or internal async, polling, blocking, or I\u002FO methods when the caller can control lifetime**. Do not make it optional on Core\u002FHelper APIs that participate in shutdown.\n  - Good: `Task\u003CIReadOnlyList\u003CSensorSnapshot>> ReadAsync(CancellationToken cancellationToken)`\n  - Bad: `Task PollAsync()` for a long-running polling loop.\n  - Too rigid: `double NormalizePercentage(double value, CancellationToken cancellationToken)` for pure CPU math.\n\n* **DO: Use `ConfigureAwait(false)` in Core and Helper library code**. Do not use it in WinUI code that must resume on the UI thread.\n  - Good: `await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);`\n  - Bad: `await process.WaitForExitAsync(cancellationToken);` in Core\u002FHelper library code.\n  - Too rigid: `await RefreshUiAsync().ConfigureAwait(false); statusText.Text = \"Ready\";`\n\n* **DON'T: Use `async void` except for event handlers**. Event handlers must catch and report exceptions at the UI or process boundary.\n  - Good: `private async void OnRefreshClicked(object sender, RoutedEventArgs args) { try { await RefreshAsync(); } catch (Exception exception) { ReportError(exception); } }`\n  - Bad: `public async void PollAsync()`\n  - Too rigid: refusing `async void` for a WinUI event handler and inventing awkward sync wrappers.\n\n* **DON'T: Block on async work with `.Result`, `.Wait()`, or `.GetAwaiter().GetResult()`** except at an explicit synchronous process boundary with a documented reason.\n  - Good: `await RunAsync(cancellationToken).ConfigureAwait(false);`\n  - Bad: `ReadAsync(cancellationToken).Result`\n  - Too rigid: rewriting a required synchronous host entry point instead of using `RunAsync(cancellationToken).GetAwaiter().GetResult(); \u002F\u002F Host requires sync entry.`\n\n* **PREFER: Return `Task` or `Task\u003CT>` by default**. Use `ValueTask\u003CT>` only for measured hot paths or APIs that usually complete synchronously and have clear single-consumption semantics.\n  - Good: `Task\u003CSensorSnapshot> ReadAsync(CancellationToken cancellationToken)`\n  - Bad: storing `ValueTask\u003CSensorSnapshot>` in a field, returning it to multiple consumers, or awaiting it twice.\n  - Too rigid: refusing `ValueTask\u003CT>` for a measured hot-path cache lookup that usually completes synchronously.\n\n* **PREFER: Use a dedicated `System.Threading.Lock` for synchronous private locks in .NET 9+ \u002F C# 13+ code**. Use async-compatible coordination, such as `SemaphoreSlim`, when the protected operation awaits.\n  - Good: `private readonly Lock _gate = new();`\n  - Bad: `private readonly object _lock = new();` in new .NET 9+ \u002F C# 13+ code without a compatibility reason.\n  - Too rigid: using `lock (_gate) { await RefreshAsync(); }` instead of `SemaphoreSlim`.\n\n* **PREFER: Match disposal syntax to the resource and scope**. Use `await using` whenever the type implements `IAsyncDisposable`, even if it also implements `IDisposable`; the synchronous path may skip async cleanup. Use `using var` when the enclosing block is the intended synchronous lifetime; use a `using (...)` statement when early disposal matters.\n  - Good: `await using HardwareMonitorSession session = await HardwareMonitorSession.OpenAsync(cancellationToken);`\n  - Bad: `using HardwareMonitorSession session = await HardwareMonitorSession.OpenAsync(cancellationToken);` when the session implements `IAsyncDisposable`.\n  - Bad: `using var session = new HardwareMonitorSession();` inside an async method when `HardwareMonitorSession` implements `IAsyncDisposable`.\n  - Too rigid: wrapping every disposable in `using (...) { }` even when method-scope `using var` is clearer and equivalent.\n\n* **CONSIDER: Use `IAsyncEnumerable\u003CT>` for real streams**. Keep one-shot snapshots as `Task\u003CIReadOnlyList\u003CT>>`.\n  - Good: `await foreach (SensorSnapshot snapshot in session.ReadSnapshotsAsync(cancellationToken)) { ... }`\n  - Bad: repeatedly returning growing `Task\u003CIReadOnlyList\u003CSensorSnapshot>>` batches for an unbounded polling stream.\n  - Too rigid: exposing `IAsyncEnumerable\u003CT>` for a single hardware snapshot request.\n\n## 5. Span And Ref Safety\n\n* **PREFER: Use `ReadOnlySpan\u003CT>` or `Span\u003CT>` for hot in-process parsing and formatting helpers**. Keep spans, `ref struct`, and `scoped` values out of JSON, IPC, UI, and long-lived domain contracts unless profiling or interop requires them.\n  - Good: `static bool TryParseSensorPath(ReadOnlySpan\u003Cchar> path, out SensorPath result)`\n  - Bad: `public ReadOnlySpan\u003Cchar> SensorPath { get; init; }` on a JSON DTO.\n  - Too rigid: changing `public required string SensorPath { get; init; }` to span-based DTO plumbing for theoretical performance.\n\n* **CONSIDER: Use `params ReadOnlySpan\u003CT>` only for low-level helpers where caller convenience avoids repeated array allocations**.\n  - Good: `static bool IsAny(SensorType value, params ReadOnlySpan\u003CSensorType> allowed)`\n  - Bad: `public SensorQuery Include(params ReadOnlySpan\u003CSensorType> sensorTypes)` on a durable public domain API.\n  - Too rigid: keeping `static bool IsAny(SensorType value, params SensorType[] allowed)` in a measured hot helper.\n\n* **CONSIDER: Use `allows ref struct` only in generic helpers that already operate on spans or other `ref struct` values**. Keep it out of ordinary domain APIs.\n  - Good: `static bool TryRead\u003CTReader>(scoped ref TReader reader) where TReader : allows ref struct`\n  - Bad: `MetricRepository\u003CT> where T : allows ref struct`\n  - Too rigid: duplicating parser helpers for each span-backed reader only to avoid `allows ref struct`.\n\n## 6. Local C# Syntax\n\n* **PREFER: Use modern argument guards and pattern null checks**. Use `ThrowIf...` helpers for ordinary parameter validation, and `is null` \u002F `is not null` for explicit null tests.\n  - Good: `ArgumentNullException.ThrowIfNull(snapshot);`\n  - Good: `if (snapshot is null) return;`\n  - Bad: `if (snapshot == null) throw new ArgumentNullException(nameof(snapshot));`\n  - Too rigid: replacing a domain-specific validation error with `ArgumentNullException.ThrowIfNull(...)`.\n\n* **DO: Follow the dotnet\u002Fruntime `var` rule**: use `var` only when the type is explicitly named on the right-hand side, typically `new` or an explicit cast. Do not use `var` for method return values, LINQ results, or built-in scalar literals.\n  - Good: `var reader = new LibreHardwareReader();`\n  - Bad: `var snapshot = reader.Read();`\n  - Bad: `var retryLimit = 3;`\n\n* **PREFER: Use target-typed `new()` only when the left-hand side explicitly names the type**.\n  - Good: `List\u003CSensorSnapshot> snapshots = new();`\n  - Bad: `List\u003CSensorSnapshot> snapshots = new List\u003CSensorSnapshot>();`\n\n* **PREFER: Use collection expressions for target-typed arrays, lists, and spans**. Avoid them when the target type is not obvious or allocation behavior matters to the code being reviewed.\n  - Good: `SensorType[] supportedTypes = [SensorType.Load, SensorType.Temperature];`\n  - Bad: `var supportedTypes = [SensorType.Load, SensorType.Temperature];`\n  - Too rigid: replacing `ImmutableArray\u003CSensorType>.Empty` with `[]` without checking the target type and allocation semantics.\n\n* **PREFER: Use LINQ method chains, not query syntax**.\n  - Good: `sensors.Where(sensor => sensor.Type == SensorType.Temperature).Select(sensor => sensor.Value)`\n  - Bad: `from sensor in sensors where sensor.Type == SensorType.Temperature select sensor.Value`\n\n* **PREFER: Use pattern matching for simple null\u002Ftype\u002Fenum dispatch**. Use `switch` expressions for value-producing dispatch; keep `switch` statements or `if` chains when side-effect order is clearer.\n  - Good: `return sensor.Type switch { SensorType.Load => \"load\", SensorType.Temperature => \"temp\", _ => \"unknown\" };`\n  - Good: `if (value is SensorSnapshot snapshot) { ... }`\n  - Bad: `SensorSnapshot? snapshot = value as SensorSnapshot; if (snapshot is not null) { ... }`\n  - Too rigid: forcing a large side-effecting workflow into a `switch` expression.\n\n* **DO: Use PascalCase for C# constants** except interop constants that intentionally mirror an external API name.\n  - Good: `private const int DefaultPollingIntervalSeconds = 1;`\n  - Bad: `private const int DEFAULT_POLLING_INTERVAL_SECONDS = 1;`\n  - Too rigid: renaming `WM_DEVICECHANGE` when intentionally mirroring Win32.\n\n* **DO: Use `nameof(...)` for strings that refer to C# members, parameters, or properties**.\n  - Good: `throw new ArgumentOutOfRangeException(nameof(pollingIntervalSeconds));`\n  - Bad: `throw new ArgumentOutOfRangeException(\"pollingIntervalSeconds\");`\n\n* **PREFER: Keep global usings limited to namespaces that are truly universal for the project**. Do not add a global using to save one local `using`.\n  - Good: `using LibreHardwareMonitor.Hardware;` only in the LHM adapter file.\n  - Bad: `global using LibreHardwareMonitor.Hardware;` for one adapter.\n  - Too rigid: banning `global using System;` in a project that consistently uses implicit\u002Fglobal base usings.\n\n## 7. Organization And Caller Readability\n\n* **PREFER: Order class members consistently**: nested types\u002Fevents, static\u002Fconst\u002Freadonly fields, instance fields\u002Fproperties, constructors, methods. Within a group, prefer `public`, `internal`, `protected`, then `private`; keep related interface implementation members together without adding `#region` unless the file already uses regions.\n  - Good: constants and fields before constructors; public API before private helpers in the same member group.\n  - Bad: private helpers before fields, constructor between unrelated methods, and interface members scattered through the class.\n  - Too rigid: moving a private helper far away from the only method that uses it when local readability is better.\n\n* **DO: Keep call sites self-explanatory when arguments are non-obvious**. Use named arguments for boolean\u002Fnull literals, named constants for repeated literals, and local variables for complex expressions.\n  - Good: `service.Start(useSsl: true);`\n  - Good: `TimeSpan timeout = TimeSpan.FromSeconds(5); client.Connect(endpoint, timeout);`\n  - Bad: `service.Start(true);`\n  - Bad: `client.Connect(endpoint, TimeSpan.FromMilliseconds(Math.Max(100, retryCount * 250)));`\n\n* **PREFER: Use the narrowest truthful collection type at API boundaries**. Inputs should not require `List\u003CT>` unless the method needs list-specific mutation or indexing. Outputs should communicate ownership: `IReadOnlyList\u003CT>` for snapshots, `List\u003CT>` when transferring a mutable container, arrays for fixed-size buffers or constants.\n  - Good: `void Publish(IReadOnlyList\u003CSensorSnapshot> snapshots)`\n  - Bad: `void Publish(List\u003CSensorSnapshot> snapshots)` when the method only enumerates.\n  - Too rigid: `IEnumerable\u003CSensorSnapshot>` when the method indexes or enumerates the sequence multiple times.\n\n* **DO: Use formatter-stable C# layout**. Use 4-space indentation, braces on control statements, one statement per line, and one blank line between members. Prefer the repo's `.editorconfig` if one is added later.\n  - Good: `if (isReady) { ... }` with braces before formatting expands it.\n  - Bad: `if (isReady) Start();`\n",{"name":5,"description":7},"main","64d15e4ac8c0ccb361e0eb16586488536cea98d7",".agents\u002Fskills\u002Fcsharp-coding-style",2,"https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics","https:\u002F\u002Fshometrics.github.io\u002F","https:\u002F\u002Fgithub.com\u002FShoMetrics","2026-10-04 14:26:56",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add ShoMetrics\u002Fsho_metrics --skill csharp-coding-style",{"tool":38,"command":39},"bunx","bunx skills add ShoMetrics\u002Fsho_metrics --skill csharp-coding-style",{"tool":41,"command":42},"pnpm","pnpm dlx skills add ShoMetrics\u002Fsho_metrics --skill csharp-coding-style","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fcsharp-coding-style\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"THIRD_PARTY_LICENSE.md","REFERENCE","参考文档",1096,"https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fcsharp-coding-style\u002FTHIRD_PARTY_LICENSE.md",[53,60,67,74,81,88],{"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},"01M75VEQBG6NEP2FV89CM1ARJ1","typescript-coding-style","Use when writing, reviewing, or changing TypeScript code in this repo, especially for TypeScript type-safety boundaries, exports, TSDoc, React Property Inspector code, and hub directory placement. Pair with coding-style for language-neutral naming, comments, tests, and ownership rules.","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftypescript-coding-style\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":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M75VEMY4JDE12D1AVSVPYB4T","technical-architecture","Read this whenever you need to make any high level code changes, understand why a design choice is made.","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftechnical-architecture\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M75VEK2SJNRYVQB9FNZY0BDR","systeminformation","Refer when you need to use the systeminformation API.","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fsysteminformation\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M75VEH4R5AQHXANPB20P5DJV","stream-deck-sdk-v2","This skill is for stream deck SDK Docs. Refer when you need to make stream deck plugin code changes.","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstream-deck-sdk-v2\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M75VEF20YS8X10DTR2XYQXTY","proto","Read this before designing\u002Fwriting .proto files. Do not read if you are simply consuming proto.","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fproto\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M75VEC96245QS2T835958R84","performance","Use when changing lifecycle hooks, polling, rendering, caching, startup, IPC, benchmarks, throttling, queueing, or any code that may run often enough to affect responsiveness or resource usage.","https:\u002F\u002Fgithub.com\u002FShoMetrics\u002Fsho_metrics\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fperformance\u002FSKILL.md",[],[]]