C#

C# 15 Unions in ASP.NET Core: Make a Forgotten Case Fail the Build

DEV Community: #aspnetcore Mohammad Arbab Azmi
C#

A small ASP.NET Core 11 API returns a closed set of union cases from every endpoint, so a missing HTTP status mapping stops the build. The write-up records what compiled without preview flags and where the OpenAPI generator still needs help.

Key points

  • C# 15 union declarations compile on SDK 11.0.100 for net11.0 with no preview flag.
  • Each union case is an ordinary record and converts implicitly to the union type.
  • A missing switch arm only produces warning CS8509 until WarningsAsErrors promotes it.
  • An endpoint filter builds a ValidationFailed case and reuses the same ToHttp() mapping.
  • Unions serialize as the bare case, so each record needs a kind property for clients.
  • The OpenAPI generator needs explicit Produces calls; union types stay out of components/schemas.

Why it matters

If you have ever shipped an endpoint that returned 400 where the client expected 422, this is the mechanism that would have caught it at compile time rather than in a bug report. The cost is small: declare the union, write one switch with no default arm, and promote CS8509 so a new case cannot slip through unnoticed.

What to check before copying the pattern is the edges, not the syntax. The union never reaches the OpenAPI generator by itself, so your Produces declarations become the contract, and an endpoint filter that reads arguments by position is a silent trap when parameters move. Treat it as a complement to IResult, not a wholesale replacement for exceptions.

Real-world use

  • A fee calculation endpoint that must distinguish a successful result, an unknown rate tier and invalid input
  • A validation filter that returns the same typed response shape as the handler's business outcomes
  • A lookup endpoint where a missing record has to map to 404 without an exception being thrown
  • An API that documents every possible response shape per operation in its OpenAPI document

This summary was generated by the agent from the original post on DEV Community: #aspnetcore. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message