C# 15 Union Types: Model Service Outcomes with Practical Examples
C# 15 union types let one return value represent several named outcomes. Use a union when the caller should explicitly handle each outcome, such as a shipment that was dispatched or placed on back order. An exhaustive switch expresses that contract at the call site.
When does a union improve a service contract?
A fulfillment service might return a status string and optional tracking fields. That shape can represent contradictory states, such as a back order with a tracking number. By declaring a separate record for each case, you attach only the relevant data to each result. The union lets a caller work with both outcomes through a common type.
| Representation | Suitable use |
|---|---|
| Enum | Outcomes carry no case-specific data |
| Union | Each outcome carries its own shape |
| Closed hierarchy | Outcomes belong to an inheritance model you control |
| Exception | An operation fails outside its normal outcome contract |
C# 15 is the default language version when targeting net11.0. Use the .NET 11 SDK and avoid opting into preview features for this sample. The released syntax and boundaries are described in the C# 15 reference.
Build a shipping outcome example
Create a console project or use the supplied project files. The example declares two records and switches on the union. It also demonstrates collection expression arguments with a case-insensitive SKU set.
Run dotnet run and expect SKU-12: 3 days. Change the input to new Dispatched("T-42") and expect Tracking: T-42. Add a new case to Shipment without updating Describe and inspect the exhaustiveness diagnostic. Treat compiler warnings according to the project policy. Avoid a catch-all arm when the purpose of the switch is to force attention to new cases.
How do other C# 15 features fit?
A closed base class limits direct derivation to the declaring assembly. Consider it when behavior and inheritance belong together. Extension indexers can provide indexed syntax through an extension. Labeled break and continue make the intended loop explicit in a nested loop. Collection expression arguments let a collection specify factory or constructor arguments while keeping its elements in the expression. The sample passes the comparer up front, so casing differences collapse to one SKU.
The separate memory-safety work remains preview. Keep it out of production assumptions about this example. For stable features and preview details, use the version-specific language documentation and the release announcement.
How should an HTTP API expose a union?
Start with the public contract. A domain union can map to stable status codes and versioned DTOs, even if the internal representation changes. If you expose a union in a JSON body, test serialization and the generated OpenAPI schema. Cases with similar JSON shapes need a reliable discriminator or classifier. Old clients should still understand existing responses after you add a new case. See the ASP.NET PB API versioning guide.
FAQ
Can I use a union to group existing record types? Yes. A shared inheritance relationship is not required for the union cases.
Why did changing the target framework affect compilation? The SDK normally selects the default language version for the target framework. Check dotnet –version and global.json if the compiler does not recognize the syntax.
Should expected validation failures throw? Model ordinary business outcomes explicitly where they belong in the contract. Reserve exceptions for the failure modes your service handles as exceptions.
Comments
Post a Comment