All the code in this series is available on GitHub. Clone it, run it, and try breaking it yourself.
georgekobaidze / dotnet11-playground
A lightweight playground repository for experimenting with and testing new features introduced in .NET 11 and C# 15.
.NET 11 & C# 15 Playground
A lightweight playground repository for experimenting with and testing new features introduced in .NET 11 and C# 15.
Use it to explore language changes, try out APIs, and validate ideas in isolation without production constraints. Each feature lives in its own small project, often with a "before" and "after" version so you can see what the new feature actually changes.
What's inside
| Project | Feature | Description |
|---|---|---|
| Unions | Union types | Console examples: the login flow (before and after unions), plus samples for parsing input, a state machine, user commands, and combining types you don't own. |
| UnionsWebApi | Union types | A minimal API that returns a union from a service and maps each outcome to an HTTP response. |
More examples will be added as new features are explored.
Getting started
You'll need the .NET 11 SDK. Then clone the repo and run any example:
dotnet run… Follow me on GitHub for more updates!
Table of Contents
- One Last Round with Unions
- 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
- When Not to Use Unions
- Wrapping Up
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:
- Parsing and validating input
- Returning results from an API
- Modeling a state machine
- Handling commands from user input
- 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 aParseErrorwith a message it can show the user. - The signature tells the truth.
ParseResult<int>says "you'll get anintor 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
intout, you have to match on the union, and the compiler makes sure theParseErrorarm 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 forParseResult<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
5115is 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.
GetUserResulttells you there are exactly three possibilities, and what each one carries. - One mechanism instead of two. No mix of
nulland exceptions. Every outcome is just a value. - The service doesn't know about HTTP.
UserServicereturns domain results, notIResultor 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
UserSuspendedcase 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
Connectedwithout aSincedate, or aFailedwithout a reason. The data and the state are the same thing. - No nullable fields.
Connected.Sinceis a plainDateTimeOffset. You never check fornullbecause the value can't be missing. - All transitions in one exhaustive
switch. ReadingNexttells you the whole state machine at a glance. - New states can't be forgotten. Add a
Reconnectingstate, and the compiler flags bothNextandDescribeuntil 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(), _ Source:https://dev.to/georgekobaidze/c-15-unpacked-practical-use-cases-for-unions-with-real-examples-e32Related posts
Why Rare-Answer Trivia Needs More Than Right or Wrong
Mechanics of AI Interface Feedback Loops: Capturing User Corrections Without Breaking UX

