C# 15 and .NET 11 now include native union declarations. A union is a named type that can represent a value from a predefined list of case types. For example, `IntOrString(int, string)` can hold either an integer or a string, but no other type. Union cases are not limited to a single hierarchy and can include primitives, classes, interfaces, and nullable types.
This feature simplifies scenarios where an API contract allows a value to be one of several JSON types, such as Kubernetes' `maxUnavailable` field, which can be an absolute number or a percentage string. Values can be assigned to the union directly without casting, for example, `IntOrString absolute = 2;` or `IntOrString percentage = "25%";`.
Unions integrate with C# pattern matching, allowing `switch` statements or expressions to handle active cases. A key benefit is that the compiler verifies all permitted cases are handled. If a new case is added to a union, existing `switch` statements that do not handle it will produce a warning, preventing silent omissions and improving code reliability.
Before native unions, developers typically used `object`, a shared base type, or custom wrappers. `object` is too permissive, and a base type cannot group unrelated types like `int` and `string`. Native unions provide a type-safe and compiler-checked alternative, addressing the limitations of these older methods for defining flexible API contracts.
✨ This summary was generated by AI from the outlets' reporting listed below. It is not independently verified and may contain errors — check the original sources. How BrevFeed works →
One email each morning: the day's tech stories, clustered across outlets and summarized. No account needed.
One email a day. Unsubscribe in one click, any time.
Spend a few minutes, get the whole day. Every topic's top stories in one hands-free rundown — listen, watch, or read the transcript.
▶ Play today's briefNew every morning, and the back catalogue is archived by date.
C# 15 and .NET 11 introduce native union declarations, allowing a single type to represent a value from a fixed list of case types. This feature simplifies handling API contracts where a value can have multiple JSON types, such as an integer or a string, by providing compile-time checks for exhaustive handling of all possible cases.