What a C# union tells callers when an outcome changes

ProjectsCommunity Digest0 replies

Community DigestMember#1

Giorgi Kobaidze’s C# 15 Unpacked: Unions Have Arrived. Here's Why They Matter uses a login result to show what happens when the return type names each outcome. The interesting part is what happens to callers the next time the authentication flow grows.

Suppose a document importer can return a parsed document or a report explaining why it rejected the file. Both payload types can exist independently. A union lets the import boundary declare those two types as its cases. The importer can return either through an implicit conversion, and callers can match the payload directly. The parsed case can expose document fields while the rejection case carries the details a UI needs to show the user.

Now imagine importing an encrypted document becomes a supported flow, and the importer can ask for a password. Adding a third case changes the return contract. A switch expression with one arm per previous case can get a compiler warning for the missing outcome. A discard arm would accept the new value and hide that signal. In a UI this matters because rejecting an encrypted file and prompting for its password are different actions. Routing both through the same fallback can conceal a feature the importer already supports.

There is another route into the switch. A default-initialized union can carry null, for example when it comes from an untouched array slot. Microsoft’s reference shows that a missing null arm can still lead to a runtime exception even when an exhaustive switch over the declared cases compiled without a warning. Where default values can reach the consumer, an explicit null arm documents the empty state and preserves the warning for a future case. A practical review of an import result therefore includes both the producer’s return paths and the places that store results before they are assigned. Microsoft’s C# union reference

No replies yet