csharp-union-types
Design, review and implement C# 15 unions and closed hierarchies in .NET 11 code. Use for union declarations, custom [Union] types, exhaustive matching, default/null handling and union serialization. Do not upgrade earlier frameworks or replace working inheritance merely because unions exist.
- License 许可
- MIT
- 最近更新
- 2026-11-10
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- csharp-union-types
- description
- Design, review and implement C# 15 unions and closed hierarchies in .NET 11 code. Use for union declarations, custom [Union] types, exhaustive matching, default/null handling and union serialization. Do not upgrade earlier frameworks or replace working inheritance merely because unions exist.
02 资源文件 50
- 参考文档.github/workflows/verify.yml948 B
- 其他.gitignore50 B
- 参考文档.sync-manifest.json5.0 KB
- 参考文档CHANGELOG.md2.7 KB
- 其他examples/.editorconfig146 B
- 其他examples/closed-hierarchies.cs1.8 KB
- 其他examples/functional.cs2.4 KB
- 其他examples/unions.cs4.1 KB
- 参考文档global.json119 B
- 许可证LICENSE1.0 KB
- 其他polyfills/IUnion.cs850 B
- 参考文档polyfills/README.md944 B
- 其他polyfills/UnionAttribute.cs969 B
- 其他probes/Directory.Build.props197 B
- 其他probes/Directory.Build.targets123 B
- 许可证probes/LICENSE1.0 KB
- 其他probes/QClosed/Program.cs2.2 KB
- 其他probes/QClosed/QClosed.csproj337 B
- 其他probes/QClosedJson/Program.cs1.7 KB
- 其他probes/QClosedJson/QClosedJson.csproj240 B
- 其他probes/QClosedLib/Library.cs620 B
- 其他probes/QClosedLib/QClosedLib.csproj207 B
- 其他probes/QConv/Program.cs5.9 KB
- 其他probes/QConv/QConv.csproj238 B
- 其他probes/QIface/Program.cs1.7 KB
- 其他probes/QIface/QIface.csproj240 B
- 其他probes/QLang/Program.cs8.9 KB
- 其他probes/QLang/QLang.csproj243 B
- 其他probes/QLang2/Program.cs6.0 KB
- 其他probes/QLang2/QLang2.csproj286 B
- 其他probes/QRoslyn/Program.cs1.9 KB
- 其他probes/QRoslyn/QRoslyn.csproj768 B
- 其他probes/QSrcGen/Program.cs1.9 KB
- 其他probes/QSrcGen/QSrcGen.csproj240 B
- 参考文档README.md4.5 KB
- 参考文档references/diagnostics.md7.8 KB
- 参考文档references/union-reference.md9.0 KB
- 参考文档references/verification.md4.9 KB
- 脚本scripts/check_links.py3.6 KB
- 脚本scripts/sync.py5.0 KB
- 脚本scripts/tests/test_tools.py5.8 KB
- 脚本scripts/verify.py17.0 KB
- 参考文档THIRD-PARTY-NOTICES.md408 B
- 其他verification/Diagnostics/Cases.cs1.5 KB
- 其他verification/Diagnostics/ClosedMetadata.cs348 B
- 其他verification/Diagnostics/Diagnostics.csproj242 B
- 其他verification/Examples/FunctionalExamples.cs6.1 KB
- 其他verification/Examples/Program.cs4.6 KB
- 其他verification/PolyfillConsumer/Consumer.cs1.9 KB
- 其他verification/PolyfillConsumer/PolyfillConsumer.csproj629 B
03 SKILL.md 正文
C# 15 unions for AI coding agents
Use unions for a finite set of alternatives whose types need not share inheritance. Use a closed class or record when existing alternatives share behavior or polymorphic serialization. Preserve open inheritance when callers must extend it.
Agent execution
- Apply the latest user request and the consuming repository's instructions. Inspect existing edits before changing code; do not overwrite unrelated work or rewrite commit authorship.
- Read only the local reference sections needed for the task. Adapt the checked examples to the project's actual types, contracts and target framework.
- Make the smallest complete change. Verify changed behavior; do not rerun unchanged probes merely to repeat an explanation. Existing reports describe their recorded run, not later untested edits.
- Commit and push when authorized. Do not watch CI or wait for publication unless requested.
- Report the concrete improvement, relevant verification and delivery status briefly. Distinguish completed work from triggered CI or publication.
Use the bundled knowledge
The skill is self-contained. For ordinary use, read only the needed local reference sections; do not fetch documentation, another repository or run all probes just to answer a covered question. The pinned compiler output and executed local examples supply the evidence. Run relevant checks when changing code or validating a version-specific claim.
Establish the compiler and contract
- Inspect the owning project,
global.json, inherited build properties and installed SDK. Do not change framework or language version without an upgrade request. - On verified SDK
11.0.100-rc.3.26522.148, unions compile withLangVersion=15.0or thenet11.0default. Earlier previews requiredpreview; do not apply that requirement to every .NET 11 SDK. Existingpreviewsettings can remain. RC3 is a security update; its release notes list no union-language changes. Distinguish the SDK compiler, the active language version and any separately referencedMicrosoft.CodeAnalysis.CSharppackage. An older Roslyn package or IDE language service can lackLanguageVersion.CSharp15even when the SDK builds C# 15 successfully. Use#error versiontemporarily to identify the compiler/language used by a build; inspect package versions separately for in-process compilation. - Identify the authoritative model and serializer. For TypeSpec or another generator, edit that source and regenerate. Never edit generated C# by hand. Separate wire and persistence models only for an explicit compatibility or storage requirement.
- Before changing serialization, record the discriminator, null representation, numeric encoding and canonical ordering. Preserve persisted bytes and hashes unless a migration is intended.
Implementation rules
- Switch on the union itself, not its object-valued
Value. Prefer a switch expression covering every case and explicitnull => throw ...when default values can arrive. A catch-all_orvarmasks future cases. An external JSON discriminator is an open input and still needs unknown-value rejection. - Completeness diagnostics are warnings. Verify that
CS8509,CS8655andCS8846fail the actual project build when completeness is required. A Roslyn test forcing warnings to errors does not establish production policy. - Switch statements lack that completeness guarantee. Removing their default arm can silently omit work, including serialization.
default(U)can contain null even when all cases are non-nullable.U?additionally has a nullable wrapper. Do not silently map an invalid default to a normal business state.- Typed patterns match contents. Untyped property/positional patterns and
varmatch the wrapper.u is { }is not a contents-presence check on a struct union; useu is not null. On RC3,u is Uis not a valid general check. - A declared union is a struct with object-backed storage and boxes value-type cases. Choose custom
[Union]storage only for a concrete requirement.HasValue/TryGetValueenable non-boxing matching but do not eliminate allocations elsewhere. Measure performance claims. - Use
readonly unionfor immutable wrappers. Record-class cases still allocate; changing those cases to record structs merely moves their allocation to boxing in generated object storage. Custom nullable scalar cases must preserve zero/false as present values and map null/default consistently across every access member. - Avoid overlapping generic success/error cases unless their conversion and matching behavior is intentional.
Task<Case>does not convert toTask<Union>; give generic factories the intended type explicitly. - For generic results, prefer distinct cases such as
Result<T>(Success<T>, Failure)when success and error payload types could coincide. The success payload remains typed asT; this does not change the generated union's object-backed storage. - For functional composition, use immutable cases and pure callbacks with
Map(transform success),Bind(compose fallible functions), andMatch(consume either case). Preserve failure values and skip success callbacks after failure. Keep expected domain errors asFailure; do not catch arbitrary callback exceptions or silently normalize an invalid default. See functional.cs. These operators do not guarantee callback purity or allocation freedom.
Closed hierarchies
Use closed when alternatives already share a base class or record, common state,
behavior, or polymorphic serialization. It restricts direct derivation to the
declaring assembly and is implicitly abstract; do not combine it with abstract,
sealed, or static.
Closure is not transitive. A normal, nonsealed child remains an extension point for
other assemblies. Mark intermediate nodes closed to extend exhaustive matching
through the hierarchy, and mark concrete leaves sealed when further derivation
is unwanted:
public closed record GateState;
public closed record GateMoving(float Percent) : GateState;
public sealed record GateOpening(float Percent) : GateMoving(Percent);
public sealed record GateClosing(float Percent) : GateMoving(Percent);
Use a switch expression that covers the leaves, with explicit null handling when null can arrive. Adding a new leaf should require updating affected matches; a catch-all would hide it. See the compiled and executed closed-hierarchy example and the hierarchy reference.
Serialization
A union declaration does not invent a JSON discriminator. Successful serialization is not proof of deserialization. Multiple object-shaped cases require an unambiguous contract and a discriminator-aware converter/classifier, or a suitable closed hierarchy with configured polymorphism. Do not classify by the first property that happens to be present.
Preserve schema-owned tags. Check every case, null/default, unknown and missing tags, and structurally similar payloads. Source-generated JSON working under JIT is not NativeAOT proof; publish and execute the relevant application for that claim. The serialization reference also covers concrete-case strictness, explicit null payloads and missing-tag exception behavior at application boundaries.
Verification
Read the reference, diagnostic catalog and verification guide. The examples in examples/unions.cs are compiled by the verifier.
scripts/verify.py uses only the bundled probe source, works in a temporary copy, and checks compiler diagnostics and runtime output, including expected failures. No Git/submodule or source download is involved. It does not run web servers or establish EF, RDG, NativeAOT or application-wide correctness. After application edits, also run the repository's own build and relevant tests.
Compiler diagnostics and executed probes are the technical verification. A separate Roslyn analyzer is optional for project-specific policies, not required for this skill. Report the SDK, checks run and remaining limits; a successful compilation alone does not prove runtime behavior.
04 同仓库更多 Skills
release
Releases .NET NuGet packages through a layered chain (library, MSBuild SDK, analyzers, consumers) without breaking restore. Use when publishing a package, bumping a lower-layer dependency in its consumers, moving a .NET SDK pin across repositories, choosing tag-driven versus push-driven publishing, setting up NuGet trusted publishing, or waiting for nuget.org to index a version before consumers restore it.
performance
Investigate .NET runtime performance using logs, metrics, traces, spans and profiles; collect crash/hang diagnostics. Use for CPU, GC, allocation or latency problems, hot-path reviews and BenchmarkDotNet comparisons. MSBuild timing belongs to msbuild; MSTest execution belongs to mstest-extensions.
nuget-versions
Manage .NET package and SDK versions, CPM migrations, Version.props ownership, global.json pins, isolated SDK installations and Renovate updates. Use for package bumps, conflicting or missing versions, NuGet restore errors and SDK selection. MSTest runner/profile semantics belong to mstest-extensions.
msbuild
Writes and reviews MSBuild evaluation, properties, items, imports, custom targets and build/buildTransitive package assets for SDK-style .NET repositories. Use for ignored or empty properties/items, generated files, analyzer/build-asset packaging, build-file reviews, binlog diagnosis and incremental-build problems. Focused MSTest project setup, runner configuration and test commands belong to mstest-extensions.
csharp-refactoring
Refactor C# and reconcile stale constants, dead checks and abandoned code, including indirect production uses. Use for renames, moves, deduplication, exhaustive cleanup, generated declarations and runtime/API contracts. MSTest test design and review belong to mstest-extensions.
audit
Audits one or more .NET repositories for build, package and analyzer problems and separates certain fixes from judgment calls. Use for repository or fleet build-policy audits, shared SDK/package consistency and cross-repository version rollouts. Focused MSTest setup, execution and test-quality reviews belong to mstest-extensions.