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(),
_ => 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.Donecarries anint, not a string that might be a number. -
Each piece has one job. The parser turns text into commands, and
TodoListruns 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. ButExecutematches on the union, so it needs no_arm and stays fully checked. -
New commands can't be half-added. Add a
Renamerecord to the union, and the compiler flagsExecuteuntil 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
intinherit from your base class. -
Type-safe, unlike
object. The signature says "anint, astringor aGuid", and the compiler enforces it at every call site. -
Exhaustive, unlike
object. No_ => throwarm. Add alongcase later, and the compiler shows you everyswitchto 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
nullargument that should never benull, 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
enumis 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 aclosedhierarchy) is often cleaner. If you find yourself writing the sameswitchin 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:
| Problem | The old workaround | The union |
|---|---|---|
| Parsing input |
bool TryParse(..., out T) or exceptions |
ParseResult<T>(T, ParseError) |
| API results |
null for one outcome, exceptions for another |
GetUserResult(User, UserNotFound, AccessDenied) |
| State machines | An enum plus nullable fields | ConnectionState(Disconnected, Connecting, Connected, Failed) |
| User commands | A big switch on strings |
Command(Add, Done, ShowList, Quit, Invalid) |
| Types you don't own |
object or wrapper classes |
ExternalId(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!

Top comments (17)
The state machine example clicked for me. Enum plus nullable fields that only make sense in some states, I've seen that mess a lot.
How would you store ConnectionState with EF Core though? JSON column?
That's my favorite example as well.
As for your question:
EF Core can't store a union directly, so you have two choices:
JSON column (via a value converter): quick to set up, but System.Text.Json writes no type discriminator by default. Cases with the same shape can get mixed up when read back, and you can't easily query by state.
Discriminator column plus mapping, which I think is the better choice. store a StateKind column with the payload in nullable columns or JSON, and convert to and from the union in one place. You can query and index the state, and adding a new state flags your mapping code at compile time.
Keep the union in your domain code, and give the database a plain, queryable shape.
Makes sense, the discriminator route is what I'd pick too. Being able to index the state matters more than saving a few columns.
And I'd keep StateKind as varchar with IsUnicode(false). Learned that one the hard way.
The parsing example raises an interesting tension: ParseError carries only a string Message, so a caller can display the reason but cannot branch on why parsing failed β distinguishing 'not a number' from 'out of range', for example, would mean parsing the message text again. Would adding a machine-readable code to ParseError, or splitting it into separate cases for each failure kind, keep the match exhaustive while letting the UI react differently to each failure? The same question applies to AccessDenied carrying a Reason string in the API example, where a 403 response might need different handling depending on the underlying reason.
Thanks for the feedback!
The API results section is the one I'd reach for first. I keep ending up with small hand-written result wrappers in command handlers, and a union would make the success and failure cases explicit without the extra class hierarchy. Do you return the union straight from a minimal API endpoint, or map it to HTTP responses in a thin layer first? I wrote up how I split handlers in ASP.NET Core here, in case it sits well next to this series: dev.to/mohammad_khalifeh/clean-arc...
You can do both - return the union or have a middleware that transforms it.
thank you i will consider it!
The UnionsWebApi minimal API example mapping each service union case straight to an HTTP response is where unions really earn their keepβmuch cleaner than juggling custom exceptions or nullable tuples just to separate 404 from validation errors.
Thanks for the feedback!
ParseError with only a string Message leaves the caller guessing which check failed. A code next to the message fixes that.
This is just a simple example to show what's possible with unions. Of course you can add more custom types to your union, including status code.
A status code in the union settles the error case cleanly. Add that one first.
adding one case to a public union being a breaking change is going to catch a lot of library authors out. that's a major version bump for one line
Good point, thatβs why using unions in libraries should be done very carefully.
I think the state machine example is the clearest use case here.
Agreed, thatβs also my favorite one.