Skip to content

C# 15 Union Types in ASP.NET Core Minimal APIs

Learn how to use C# 15 union types in ASP.NET Core 11 Minimal APIs. We declare unions, use exhaustive pattern matching, accept and return them as JSON, see how they show up in OpenAPI, and compare them with closed class hierarchies.

Ivan GechevIvan GechevSoftware Developer
Published on
Reading time
14 min read
On this page

For years, every time we needed a value that could be "one of these few things", we had to pick our poison. We could create a base class and hope nobody adds an unexpected subtype. We could return object and cast our way through it. Or we could pull in a library like OneOf and learn its API.

C# 15 finally gives us a proper answer with union types. We declare a closed set of types a value can be, the compiler makes sure we handle every one of them, and with .NET 11, System.Text.Json and ASP.NET Core understand them out of the box.

In this article, we'll start with the basics of declaring and using unions, then we'll put them to work in a Minimal API, both as response and request types. After that, we'll see how they show up in our OpenAPI documents, look at their limitations, and finish by comparing them with the new closed class hierarchies. As usual, we'll use a cat-themed API to demonstrate each concept.

Let's dive in!

The Problem Unions Solve

Let's say our cat API tracks what each cat ate last. A meal can be dry food, measured in grams, or wet food, measured in pouches. Those are two different shapes of data.

Before .NET 11, the cleanest way to model this in an API was polymorphism:

Meal.cs
C#
[JsonPolymorphic]
[JsonDerivedType(typeof(DryFood), "dry")]
[JsonDerivedType(typeof(WetFood), "wet")]
public abstract record Meal(string Brand);

public record DryFood(string Brand, int Grams) : Meal(Brand);

public record WetFood(string Brand, int Pouches) : Meal(Brand);

This works, but it comes with a few strings attached. Both types have to share a base class. Every derived type has to be registered by hand with the [JsonDerivedType] attribute. And our clients have to send and read a $type discriminator property, which leaks an implementation detail into our API contract.

On top of that, the compiler doesn't know that DryFood and WetFood are the only meals. Anybody can create a new type that inherits from Meal, so every switch needs a fallback _ arm, just in case.

Declaring a Union Type in C# 15

With C# 15, we can describe the same idea directly. First, we define our two case types:

Meal.cs
C#
public record DryFood
{
	public required string Brand { get; init; }
	public required int Grams { get; init; }
}

public record WetFood
{
	public required string Brand { get; init; }
	public required int Pouches { get; init; }
}

These are plain records with no base class and no attributes. Note that we mark the properties as required. We'll see why that matters once we start receiving meals as JSON.

Then, we declare the union using the new union keyword:

Meal.cs
C#
public union Meal(DryFood, WetFood);

That's it. A Meal is now either a DryFood or a WetFood, and nothing else. The case types can be pretty much anything: classes, records, structs, interfaces, or even primitives, so something like public union IntOrString(int, string); is perfectly valid.

Behind the scenes, the compiler turns our union declaration into a struct that holds the actual value in an object? Value property and has a constructor for each case type. We don't have to care about that most of the time, but it's good to know that a union is a lightweight wrapper and not a class hierarchy.

Creating Union Values

We never have to call the Meal constructor ourselves. Each case type implicitly converts to the union:

Program.cs
C#
Meal breakfast = new DryFood { Brand = "Crunchy Paws", Grams = 60 };
Meal dinner = new WetFood { Brand = "Tuna Delight", Pouches = 2 };

Console.WriteLine(breakfast.Value); // DryFood { Brand = Crunchy Paws, Grams = 60 }

We simply assign a DryFood or WetFood instance to a Meal variable, and the compiler does the rest. If we try to assign anything else, like a string, we get a compile-time error.

Exhaustive Pattern Matching

This is where unions really shine. Let's calculate the calories in a meal:

Program.cs
C#
static int CountCalories(Meal meal) => meal switch
{
	DryFood dry => dry.Grams * 4,
	WetFood wet => wet.Pouches * 70,
};

Notice something? There's no discard _ arm. The compiler knows that a Meal can only be DryFood or WetFood, so this switch expression is exhaustive.

The type patterns also test the contents of the union, not the union itself. We write DryFood dry and get a DryFood back, without having to touch the Value property.

Now, imagine we add a third case, public union Meal(DryFood, WetFood, RawFood);. Every switch that doesn't handle RawFood immediately gets a compiler warning. With the old base class approach, the new type would silently fall through to the _ arm, and we'd find out in production.

Adding Members to a Union

Unions can also have a body, so we can move our calorie logic right into the type:

Meal.cs
C#
public union Meal(DryFood, WetFood)
{
	public int Calories => this switch
	{
		DryFood dry => dry.Grams * 4,
		WetFood wet => wet.Pouches * 70,
		_ => throw new InvalidOperationException("The meal has no value.")
	};
}

We add a computed Calories property that switches on this.

This time, we do add a fallback arm, and here's why. Because a union is a struct, default(Meal) is a valid value, and a default union contains null. The official docs use the same pattern for union members. If you skip it, a default value would throw a SwitchExpressionException anyway, so I prefer to throw an exception with a clear message.

There are a few rules for union bodies. We can add methods and computed properties, but not instance fields, auto-properties, or field-like events. That makes sense, as the union only holds one thing: its value.

Returning Unions From Minimal API Endpoints

Now, let's put our Meal union to work. We'll keep things simple and store the last meal of each cat in memory:

Program.cs
C#
var lastMeals = new ConcurrentDictionary<int, Meal>
{
	[1] = new DryFood { Brand = "Crunchy Paws", Grams = 60 },
	[2] = new WetFood { Brand = "Tuna Delight", Pouches = 2 }
};

var catRoutes = app.MapGroup("api/cats");

Here, we create a ConcurrentDictionary and seed it with one meal of each kind. Notice how we can assign both DryFood and WetFood instances to it, thanks to the implicit conversions.

Then, we create a GET endpoint that returns the last meal of a cat:

Program.cs
C#
catRoutes.MapGet("{id:int}/last-meal", Results<Ok<Meal>, NotFound> (int id) =>
{
	return lastMeals.TryGetValue(id, out var meal)
		? TypedResults.Ok(meal)
		: TypedResults.NotFound();
});

If you've read my Minimal API Response Types: Produces<T> vs TypedResults post, this will look very familiar. We use Results<Ok<Meal>, NotFound> as the return type and TypedResults to create the responses.

It's worth pointing out that these are two different kinds of "union" working together. Results<T1, T2> describes which HTTP results an endpoint can return. Our C# union describes the shape of the data inside a successful response. One doesn't replace the other.

Let's call our endpoint:

curl --location 'https://localhost:7298/api/cats/1/last-meal'

And we get:

JSON
{
    "brand": "Crunchy Paws",
    "grams": 60
}

There's no wrapper, no value property, and no $type discriminator. System.Text.Json serializes a union as its active case, so our clients just see a dry food object.

If we request the meal for the cat with an ID of 2, we get a wet food object with a pouches property instead. Same endpoint, same return type, different shapes.

If you are interested in having a deep dive into Minimal APIs, you can check my Minimal APIs in ASP.NET Core course here.

Returning unions is easy, as the serializer always knows which case it's holding. Accepting them is a bit more interesting.

Accepting Unions as Request Bodies

Let's add an endpoint for logging a new meal:

Program.cs
C#
catRoutes.MapPost("{id:int}/meals", (int id, Meal meal) =>
{
	lastMeals[id] = meal;

	return TypedResults.Ok(new MealLogged(id, meal, meal.Calories));
});

We accept a Meal from the request body, store it, and return a MealLogged response with the calculated calories:

MealLogged.cs
C#
public record MealLogged(int CatId, Meal Meal, int Calories);

Now, here's the catch. When System.Text.Json deserializes a union, it has to figure out which case the JSON represents. By default, it decides by looking at the JSON token type: a number, a string, a Boolean, an array, or an object.

That works great for something like IntOrString, but both of our meals are JSON objects. They share the same token type, so the default classifier can't tell them apart. The source generator even reports a diagnostic for ambiguous unions like this one.

Using the Structural Classifier

To solve this, .NET 11 ships with a built-in structural classifier. We enable it with the [JsonUnion] attribute:

Meal.cs
C#
[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union Meal(DryFood, WetFood)
{
	// ...
}

The JsonUnionAttribute lives in the System.Text.Json.Serialization namespace. It doesn't turn a type into a union, it only selects a classifier for an existing one.

The structural classifier starts with all object cases as candidates and narrows them down as it reads the property names in the JSON payload. Required properties that are missing remove a case from the list. And this is exactly why we marked our properties as required earlier. A payload without grams can't be a DryFood, and a payload without pouches can't be a WetFood. Classification succeeds only when exactly one case remains.

Let's log some wet food for our cat:

curl --location 'https://localhost:7298/api/cats/1/meals' \
--header 'Content-Type: application/json' \
--data '{
    "brand": "Tuna Delight",
    "pouches": 3
}'

Our API responds with:

JSON
{
    "catId": 1,
    "meal": {
        "brand": "Tuna Delight",
        "pouches": 3
    },
    "calories": 210
}

The classifier picked WetFood, and our Calories property did the math.

Now, what happens if we send something that matches neither case, or both?

curl --location 'https://localhost:7298/api/cats/1/meals' \
--header 'Content-Type: application/json' \
--data '{
    "brand": "Mystery Mix"
}'

The payload has neither grams nor pouches, so both cases get removed. The serializer throws a JsonException, and Minimal APIs treat it like any other malformed JSON body. We get a 400 Bad Request and our handler never runs. In development, the exception page tells us exactly what went wrong:

Microsoft.AspNetCore.Http.BadHttpRequestException: Failed to read parameter "Meal meal" from the request body as JSON.
 ---> System.Text.Json.JsonException: The custom type classifier for union type 'Meal' returned null for JSON token type 'StartObject'.

The same happens if we send both grams and pouches. Both cases keep their required properties, two candidates remain, and the classifier refuses to guess.

Important: The structural classifier only looks at root-level property names. It doesn't inspect property values, nested objects, or array elements. Also be careful when renaming properties, because that can change which case a payload matches.

Watch Out for Primitive Unions in Request Bodies

There's one more gotcha. Minimal APIs use JsonSerializerDefaults.Web, and the web defaults allow reading numbers from JSON strings. That means a union like IntOrString(int, string) works perfectly fine as a response type, but as a request body, a JSON string like "42" can be either an int or a string. The serializer can't pick one and throws an exception.

If you need a primitive union as an input, you'll have to write a custom classifier by deriving from JsonTypeClassifierFactory. For most APIs, I'd rather use object cases with distinct required properties and let the structural classifier do the work.

Union Types in OpenAPI Documents

If we add OpenAPI support to our project:

Program.cs
C#
builder.Services.AddOpenApi();

// ...

app.MapOpenApi();

Our union shows up as an anyOf schema that references each case type:

JSON
"Meal": {
    "type": "object",
    "anyOf": [
        { "$ref": "#/components/schemas/DryFood" },
        { "$ref": "#/components/schemas/WetFood" }
    ]
}

Unlike polymorphic types, union cases don't carry a $type discriminator. So each case reuses its own standalone schema component instead of a duplicated, prefixed one. ApiExplorer detects unions through JsonTypeInfoKind.Union, so this also works with Swashbuckle and NSwag if you still use them.

Client generators that understand anyOf can now produce proper types for our API, without us documenting anything by hand.

Limitations of Union Types in ASP.NET Core

Unions are a great addition, but there are a few things they can't do yet.

Only JSON Bodies Are Supported

Unions only work with binding sources that go through System.Text.Json. Route values, query strings, headers, and form fields aren't supported. These values arrive as plain strings, and there's no reliable way to decide which case a string like "42" should become.

If you need a union-like value from the route or the query string, bind a string and create the union yourself in the handler.

Some Case Combinations Aren't Supported

The serializer can't distinguish multiple non-object cases that use the same JSON token type. For example, Guid and string both serialize as JSON strings, so a union Identifier(Guid, string) can't be deserialized. Nested unions and polymorphic case types aren't supported either.

The good news is that a configuration that can't distinguish its cases fails fast. The serializer throws a NotSupportedException when it builds the classifier, and the source generator reports a diagnostic at compile time.

SignalR Needs the JSON Protocol

If you use SignalR, unions only work with the JSON hub protocol. The MessagePack and Newtonsoft.Json protocols don't support them.

Unions vs Closed Class Hierarchies

C# 15 also introduces closed class hierarchies, and they solve a very similar problem:

Treat.cs
C#
[JsonPolymorphic(InferClosedTypePolymorphism = true)]
public closed record Treat;

public sealed record Catnip(int Grams) : Treat;

public sealed record Tuna(int Flakes) : Treat;

The closed modifier means that only types in the same assembly can directly derive from Treat. A closed class is implicitly abstract, and because the compiler knows all of its direct subtypes, a switch over Treat is exhaustive too.

We also add [JsonPolymorphic(InferClosedTypePolymorphism = true)]. This tells System.Text.Json to find the derived types on its own, so we no longer have to list them with [JsonDerivedType]. Serializing a Catnip treat gives us {"$type":"Catnip","grams":5}.

Note that the closed modifier alone doesn't add a discriminator. You have to opt in with InferClosedTypePolymorphism, either per hierarchy or globally through JsonSerializerOptions.

So, which one should you use? Here's how I think about it:

Union TypesClosed Hierarchies
Case types need a shared base class❌✅
Cases can be primitives or types you don't own✅❌
Exhaustive switch✅✅
JSON discriminator❌ (classified by shape)✅ ($type)
Cases can share data and behavior❌✅
Runtime representationstruct wrapperClass hierarchy

I plan on reaching for unions when the cases are unrelated types, when some of them aren't mine, or when I want clean JSON without a $type property. I use closed hierarchies when the cases are clearly variations of the same concept, share properties, and I'm happy with an explicit discriminator. That one is also the safer choice when the JSON shapes of the cases are too similar for the structural classifier.

Conclusion

Union types are one of the biggest additions to C# in years. They let us say exactly what a value can be, the compiler holds us to it with exhaustive pattern matching, and in .NET 11, System.Text.Json, Minimal APIs, and OpenAPI support them out of the box.

For Minimal APIs, returning unions just works. Accepting them requires a bit more thought: object cases need the structural classifier and distinct required properties, and primitive unions don't play well with the web defaults. As long as we keep those rules in mind, unions give us cleaner contracts than the polymorphic base classes we've been using so far.

Frequently Asked Questions

Do I need to enable a preview feature to use union types?

No. C# 15 is the default language version for projects that target net11.0, and union types are a fully supported feature.

Are union types classes or structs?

The compiler turns a union declaration into a struct with a Value property of type object?. Value-type cases, like int, are boxed.

Why do I need the [JsonUnion] attribute on my union?

You only need it when the default classifier can't tell the cases apart, for example, when two cases are both JSON objects. Unions like IntOrString work without it, except as request bodies with the web defaults.

Can I bind a union from the route or the query string?

No. Unions are only supported for JSON request bodies. Bind a string and create the union in your handler instead.

What happens if a request body doesn't match any union case?

The serializer throws a JsonException, and the request is rejected with a 400 Bad Request before your handler runs.

Can union types replace Results<T1, T2> in Minimal APIs?

No, they complement each other. Results<T1, T2> describes the possible HTTP results of an endpoint, while a union describes the possible shapes of the data in a response.

> keep reading

13 min read

Async Validation in .NET 11 Minimal APIs

Learn how to use the new async validation support in .NET 11 Minimal APIs with AsyncValidationAttribute and IAsyncValidatableObject to run database-backed validation rules before your endpoint handlers even execute.