Vyntrise Technologies logoVyntrise Technologies

C# 15 Unpacked: Practical Use Cases for Unions with Real Examples

November 23, 2026
By Giorgi Kobaidze
Original Source
Share:

AI Summary

> **All the code in this series is available on GitHub. Clone it, run it, and try breaking it yourself.** {% embed https://github.com/georgekobaidze/dotnet11-playground %} Follow me on GitHub for more updates! --- ## Table of Contents - [One Last Round with Unions](#one-last-round-with-unions)...

C# 15 Unpacked: Practical Use Cases for Unions with Real Examples

All the code in this series is available on GitHub. Clone it, run it, and try breaking it yourself.

{% embed https://github.com/georgekobaidze/dotnet11-playground %}

Follow me on GitHub for more updates!


Table of Contents


One Last Round with Unions

The last two articles in this series were all about unions. In the first one, we looked at what unions are and whether we actually need them. In the second one, we popped the hood and found a struct.

.NET 11 has a lot more to offer, so I promise this is the last union article in the series.

And this time, it's all about practice. We're software engineers. We don't really trust a new feature until we've used it to solve a real problem. That's where its value shows up.

So no theory and no IL this time. Just five common problems, the workarounds we've all written for them, and how unions solve each one better:

  1. Parsing and validating input
  2. Returning results from an API
  3. Modeling a state machine
  4. Handling commands from user input
  5. Combining types you don't own

Every example is runnable, and all the code is in the GitHub repository.

The four console examples live in src/Unions (uncomment the one you want in Program.cs), and the API example is a separate project in src/UnionsWebApi:

dotnet run --project src/Unions dotnet run --project src/UnionsWebApi

1. Parsing and Validating Input

Every app takes input it can't trust: console input, query strings, config files, CSV rows. Parsing can go wrong in more than one way, and the caller usually needs to know which way.

Let's parse a user's age. It has to be a number, and it has to be realistic.

The Old Way

The classic TryParse pattern tells you that something failed, but not why:

static bool TryParseAge(string input, out int age) { if (!int.TryParse(input, out age)) return false; return age is >= 0 and <= 150; }

Was it "abc"? Was it "-5"? The caller gets false and has to guess, so the user sees a vague "Invalid age."

The other classic approach is to throw:

static int ParseAge(string input) { if (!int.TryParse(input, out int age)) throw new FormatException($"'{input}' is not a number."); if (age is < 0 or > 150) throw new ArgumentOutOfRangeException(nameof(input), $"{age} is not a realistic age."); return age; }

Now we have the reason, but we're using exceptions for something that happens all the time. Users mistype things constantly. Nothing in the signature warns the caller to catch them, either. int ParseAge(string) looks like it always succeeds.

The Union Way

public record ParseError(string Message); public union ParseResult<T>(T, ParseError); public static class AgeParser { public static ParseResult<int> Parse(string input) { if (!int.TryParse(input, out int age)) return new ParseError($"'{input}' is not a number."); if (age is < 0 or > 150) return new ParseError($"{age} is not a realistic age."); return age; } }

And a small console loop to try it out:

while (true) { Console.Write("Enter your age: "); string? input = Console.ReadLine(); if (input is null) break; // the input stream was closed (Ctrl+Z on Windows, Ctrl+D on macOS/Linux) string message = AgeParser.Parse(input) switch { int age => $"Got it, you're {age}.", ParseError error => $"Oops: {error.Message}" }; Console.WriteLine(message); }

Type 34, then abc, then 200, and you get a clear answer for each.

Why It's Better

  • The reason travels with the result. Instead of a bare false, the caller gets a ParseError with a message it can show the user.
  • The signature tells the truth. ParseResult<int> says "you'll get an int or an error" right in the method signature. Nobody has to read the implementation to find out what can go wrong.
  • You can't forget the failure case. To get the int out, you have to match on the union, and the compiler makes sure the ParseError arm is there.
  • No exceptions for normal input. Bad input is expected, not exceptional. Exceptions stay reserved for real bugs.
  • It's reusable. ParseResult<T> is generic, so the same union works for ParseResult<DateOnly>, ParseResult<Uri>, or anything else you parse.

2. Returning Results from an API

Most API endpoints have more than one outcome. Looking up a user, for example: the user exists, the user doesn't exist, or the user exists but you're not allowed to see them.

The Old Way

Usually, each outcome gets a different mechanism. "Not found" becomes null. "Forbidden" becomes an exception:

public User? GetUser(int id) { if (!_users.TryGetValue(id, out User? user)) return null; if (user.Id == AdminId) throw new UnauthorizedAccessException("Admin profiles are private."); return user; }

And the endpoint has to deal with both:

app.MapGet("/users/{id}", (int id, UserService users) => { try { User? user = users.GetUser(id); return user is null ? Results.NotFound() : Results.Ok(user); } catch (UnauthorizedAccessException ex) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status403Forbidden); } });

The signature User? GetUser(int id) only tells half the story. You can guess that null means "not found", but nothing tells you about the exception. Forget the try/catch, and a perfectly normal "you can't see this" turns into a 500 error.

The Union Way

public record User(int Id, string Name); public record UserNotFound(int Id); public record AccessDenied(string Reason); public union GetUserResult(User, UserNotFound, AccessDenied); public class UserService { private const int AdminId = 100; private readonly Dictionary<int, User> _users = new() { [1] = new User(1, "Ada"), [2] = new User(2, "Linus"), [AdminId] = new User(AdminId, "Admin"), }; public GetUserResult GetUser(int id) { if (!_users.TryGetValue(id, out User? user)) return new UserNotFound(id); if (user.Id == AdminId) return new AccessDenied("Admin profiles are private."); return user; } }

And the endpoint maps each outcome to an HTTP response in one place:

var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton<UserService>(); var app = builder.Build(); app.MapGet("/users/{id}", (int id, UserService users) => users.GetUser(id) switch { User user => Results.Ok(user), UserNotFound notFound => Results.NotFound($"User {notFound.Id} doesn't exist."), AccessDenied denied => Results.Problem(denied.Reason, statusCode: StatusCodes.Status403Forbidden) }); app.Run();

Run it and try all three outcomes:

curl -i http://localhost:5115/users/1 # 200 OK curl -i http://localhost:5115/users/99 # 404 Not Found curl -i http://localhost:5115/users/100 # 403 Forbidden

Note: Port 5115 is what the app uses on my machine. Your port may be different, especially if you created your own project. Use the URL printed in the console when the app starts.

Why It's Better

  • Every outcome is in the signature. GetUserResult tells you there are exactly three possibilities, and what each one carries.
  • One mechanism instead of two. No mix of null and exceptions. Every outcome is just a value.
  • The service doesn't know about HTTP. UserService returns domain results, not IResult or status codes. The endpoint decides how each one becomes a response, so the same service works for a gRPC call, a background job, or a test.
  • New outcomes can't slip through. Add a UserSuspended case later, and the compiler flags the endpoint until you decide what HTTP status it gets.

Why not Results.Forbid()? It looks like the obvious choice for a 403, but it hands the request to the authentication system. If your app has no authentication configured, it throws at runtime. Results.Problem(..., statusCode: 403) works everywhere.


3. Modeling a State Machine

Lots of things in software move through states: a network connection, an order, a payment, a background job. Each state usually comes with its own data. A connection that's connecting knows which attempt it's on. A connected one knows when it connected. A failed one knows why.

The Old Way

The usual approach is an enum for the state, plus a property for every piece of data any state might need:

public enum ConnectionStatus { Disconnected, Connecting, Connected, Failed } public class Connection { public ConnectionStatus Status { get; set; } public int? Attempt { get; set; } // only when Connecting public DateTimeOffset? ConnectedSince { get; set; } // only when Connected public string? FailureReason { get; set; } // only when Failed }

Those comments are doing a lot of work. Nothing stops Status from being Connected while ConnectedSince is null and FailureReason is set. Every reader has to remember which fields are valid in which state, and every property is nullable, so the code fills up with ? and !.

Even the switch can't be fully trusted:

string Describe(Connection c) => c.Status switch { ConnectionStatus.Disconnected => "Offline", ConnectionStatus.Connecting => $"Connecting (attempt {c.Attempt})...", ConnectionStatus.Connected => $"Online since {c.ConnectedSince:T}", ConnectionStatus.Failed => $"Failed: {c.FailureReason}", _ => "Unknown" };

An enum is just a number underneath, so (ConnectionStatus)42 is a valid value. The compiler warns unless you add a _ arm, and that arm swallows any new state you add later.

The Union Way

Each state becomes a record that carries only its own data:

public record Disconnected; public record Connecting(int Attempt); public record Connected(DateTimeOffset Since); public record Failed(string Reason); public union ConnectionState(Disconnected, Connecting, Connected, Failed);

The transitions live in one place:

public static class ConnectionMachine { private const int MaxAttempts = 3; public static ConnectionState Next(ConnectionState state, bool serverResponds) => state switch { Disconnected => new Connecting(1), Connecting when serverResponds => new Connected(DateTimeOffset.Now), Connecting c when c.Attempt < MaxAttempts => new Connecting(c.Attempt + 1), Connecting => new Failed($"No response after {MaxAttempts} attempts."), Connected when serverResponds => state, Connected => new Disconnected(), Failed => new Disconnected() }; public static string Describe(ConnectionState state) => state switch { Disconnected => "Offline", Connecting c => $"Connecting (attempt {c.Attempt})...", Connected c => $"Online since {c.Since:T}", Failed f => $"Failed: {f.Reason}" }; }

And a small loop lets you play the server:

ConnectionState state = new Disconnected(); while (true) { Console.WriteLine($"State: {ConnectionMachine.Describe(state)}"); Console.Write("Does the server respond? (y/n): "); string? input = Console.ReadLine(); if (input is null) break; // the input stream was closed (Ctrl+Z on Windows, Ctrl+D on macOS/Linux) state = ConnectionMachine.Next(state, serverResponds: input.Trim().ToLower() == "y"); Console.WriteLine(); }

Answer n three times while connecting and watch it fail. Answer y and it connects. Answer n while connected and it drops back to offline.

Why It's Better

  • Impossible states can't exist. There's no way to build a Connected without a Since date, or a Failed without a reason. The data and the state are the same thing.
  • No nullable fields. Connected.Since is a plain DateTimeOffset. You never check for null because the value can't be missing.
  • All transitions in one exhaustive switch. Reading Next tells you the whole state machine at a glance.
  • New states can't be forgotten. Add a Reconnecting state, and the compiler flags both Next and Describe until you handle it. No _ arm to hide it.

4. Handling Commands from User Input

Command-line tools, chat bots and game consoles all do the same thing: read a line of text, figure out which command it is, and run it. The parsing and the running tend to get tangled together.

Let's build a tiny to-do list with four commands: add, done, list and quit.

The Old Way

The usual approach is one big switch on strings, with parsing, validation and execution all mixed together:

switch (parts[0]) { case "add": if (parts.Length < 2) { Console.WriteLine("What should I add?"); break; } items.Add(parts[1]); break; case "done": if (parts.Length < 2 || !int.TryParse(parts[1], out int number)) { Console.WriteLine("Which item?"); break; } items.RemoveAt(number - 1); break; case "list": // print the items... break; case "quit": return; default: Console.WriteLine("Unknown command."); break; }

It works for four commands. At fifteen, it's a wall of code. The command logic can't be tested without the console, "add" is just a string that's easy to mistype, and adding a new command means digging through the whole block.

The Union Way

First, each command becomes a record that carries exactly the data it needs:

public record Add(string Text); public record Done(int Number); public record ShowList; public record Quit; public record Invalid(string Reason); public union Command(Add, Done, ShowList, Quit, Invalid);

Then parsing happens in one place, and only there:

public static class CommandParser { public static Command Parse(string input) { string[] parts = input.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) return new Invalid("Type a command: add, done, list or quit."); string argument = parts.Length > 1 ? parts[1] : ""; return parts[0].ToLowerInvariant() switch { "add" when argument.Length > 0 => new Add(argument), "add" => new Invalid("What should I add? Try: add Buy milk"), "done" when int.TryParse(argument, out int number) => new Done(number), "done" => new Invalid("Which item? Try: done 1"), "list" => new ShowList(), "quit" => new Quit(), _ => new Invalid($"Unknown command '{parts[0]}'.") }; } }

And running a command never deals with strings again:

public class TodoList { private readonly List<string> _items = []; public string Execute(Command command) => command switch { Add add => AddItem(add.Text), Done done => Complete(done.Number), ShowList => Show(), Quit => "Bye!", Invalid invalid => invalid.Reason }; private string AddItem(string text) { _items.Add(text); return $"Added: {text}"; } private string Complete(int number) { if (number < 1 || number > _items.Count) return $"There's no item {number}."; string item = _items[number - 1]; _items.RemoveAt(number - 1); return $"Done: {item}"; } private string Show() => _items.Count == 0 ? "Nothing to do. Nice!" : string.Join(Environment.NewLine, _items.Select((item, i) => $"{i + 1}. {item}")); }

Finally, the loop that ties it together:

var todo = new TodoList(); Console.WriteLine("Commands: add <text>, done <number>, list, quit"); while (true) { Console.Write("> "); string? line = Console.ReadLine(); if (line is null) break; // the input stream was closed (Ctrl+Z on Windows, Ctrl+D on macOS/Linux) Command command = CommandParser.Parse(line); Console.WriteLine(todo.Execute(command)); if (command is Quit) break; }

Try add Buy milk, add Write the next article, list, done 1, and list again.

Why It's Better

  • Parse once, then work with types. Text only exists at the edge, in CommandParser. Everything after that works with real types. Done carries an int, not a string that might be a number.
  • Each piece has one job. The parser turns text into commands, and TodoList runs them. You can test the parser without a to-do list, and the to-do list without a console.
  • The _ arm stays where it belongs. Strings can be anything, so the parser needs a fallback. But Execute matches on the union, so it needs no _ arm and stays fully checked.
  • New commands can't be half-added. Add a Rename record to the union, and the compiler flags Execute until you handle it. You can't forget the second half of the work.

5. Combining Types You Don't Own

Sometimes a value can be one of several types you didn't write and can't change. Think of IDs coming from different systems: an old database uses int, the CRM uses string codes, and the new cloud service uses Guid.

The Old Way

Option one is to give up on types and use object:

static string ToKey(object id) => id switch { int number => $"legacy-{number}", string code => $"crm-{code}", Guid guid => $"cloud-{guid:N}", _ => throw new ArgumentException($"Unsupported ID type: {id.GetType().Name}") };

The signature accepts anything. ToKey(3.14) and ToKey(DateTime.Now) both compile, and you only find out at runtime.

Option two is to wrap every type in your own hierarchy:

public abstract record ExternalId; public sealed record LegacyId(int Value) : ExternalId; public sealed record CrmId(string Value) : ExternalId; public sealed record CloudId(Guid Value) : ExternalId;

That's type-safe, but now you need three wrapper classes for values that were perfectly fine on their own, and every caller has to write new LegacyId(1042) instead of just 1042.

The Union Way

public union ExternalId(int, string, Guid);

That's it. No wrappers, no base class. int, string and Guid are case types as they are:

public static class IdMapper { public static ExternalId Parse(string input) { input = input.Trim(); if (int.TryParse(input, out int number)) return number; if (Guid.TryParse(input, out Guid guid)) return guid; return input; } public static string ToKey(ExternalId id) => id switch { int number => $"legacy-{number}", string code => $"crm-{code}", Guid guid => $"cloud-{guid:N}" }; }

A small loop to try it:

while (true) { Console.Write("Enter an ID: "); string? input = Console.ReadLine(); if (input is null) break; // the input stream was closed (Ctrl+Z on Windows, Ctrl+D on macOS/Linux) ExternalId id = IdMapper.Parse(input); Console.WriteLine($"Key: {IdMapper.ToKey(id)}"); }

Try 1042, ACME-77, and a GUID like 3f2504e0-4f89-11d3-9a0c-0305e82c3301.

Compare that to the object version. There, ToKey(3.14) compiles fine and only crashes at runtime, when the _ => throw arm fires. With the union, the same mistake doesn't even compile:

IdMapper.ToKey(1042); // ✅ an int: compiles IdMapper.ToKey("ACME-77"); // ✅ a string: compiles IdMapper.ToKey(3.14); // ❌ a double: compile error, double isn't one of the case types

Why It's Better

  • No wrapper classes. Types you don't own can be case types directly. No class hierarchy can do that, because you can't make int inherit from your base class.
  • Type-safe, unlike object. The signature says "an int, a string or a Guid", and the compiler enforces it at every call site.
  • Exhaustive, unlike object. No _ => throw arm. Add a long case later, and the compiler shows you every switch to update.

One Thing to Keep in Mind: Boxing

As we saw in the previous article, a union stores its value in an object? Value property. int and Guid are value types, so every time an ExternalId holds one, the value gets boxed: copied into a small object on the heap.

For mapping IDs, parsing input, or handling API results, that cost doesn't matter. In a hot loop that processes millions of values, it might. In that case, you can write your own union struct with the [Union] attribute and add HasValue and TryGetValue members. The compiler then uses those for pattern matching and skips the boxing. For everyday code, the plain union keyword is the right choice.


When Not to Use Unions

Unions are a great tool, but not for everything. A few cases where something else fits better:

  • When the failure is a bug. A null argument that should never be null, or a broken invariant, is exceptional. Throw an exception. Unions are for outcomes the caller is expected to handle, like bad input or a missing user, not for things that should never happen.
  • When the cases carry no data. If you only need "red, yellow or green" with nothing attached, a plain enum is simpler. Unions start paying off when each case carries different data.
  • When the cases share behavior. If every case needs the same method, like Area() for different shapes, a class hierarchy with a virtual method (or a closed hierarchy) is often cleaner. If you find yourself writing the same switch in five places just to call "the same thing" on each case, that's a sign.
  • In public library APIs that will grow. Adding a case to a public union breaks every consumer's exhaustive switch. That's great inside your own codebase, where the compiler shows you what to fix. For a library used by people you don't know, it's a breaking change.
  • In hot paths with value-type cases. Remember the boxing from use case 5. Measure first. If it matters, use a custom [Union] struct or a different design.

And one rule for wherever you do use them: dispatch with switch expressions. Classic switch statements and if/else chains don't get exhaustiveness checking, so the safety net only works if you use it.


Wrapping Up

Five problems, five workarounds we've all written, and five unions that replaced them:

ProblemThe old workaroundThe union
Parsing inputbool TryParse(..., out T) or exceptionsParseResult<T>(T, ParseError)
API resultsnull for one outcome, exceptions for anotherGetUserResult(User, UserNotFound, AccessDenied)
State machinesAn enum plus nullable fieldsConnectionState(Disconnected, Connecting, Connected, Failed)
User commandsA big switch on stringsCommand(Add, Done, ShowList, Quit, Invalid)
Types you don't ownobject or wrapper classesExternalId(int, string, Guid)

In every case, the pattern is the same: a union turns "what can happen here?" from a comment, a convention or a guess into something the compiler knows and checks for you.

That wraps up unions in this series. We've seen what they are, what they compile to, and how to put them to work. .NET 11 has plenty more to explore, so stay tuned.

All the code from this article is in the GitHub repository. Clone it, run the examples, and try adding a new case to each union. Watching the compiler point out everything you forgot is half the fun.

Which of these five would you use first in your own code? Let me know in the comments.


Let's stay connected!