How does a Results<Ok<ReturnLabel>, NotFound, Conflict<string>> return type work in an ASP.NET Core Minimal API handler, and what are its limits?
answer
- implicit conversion from each type argument
- private constructor, Result property
- metadata from every type argument
- two to six result types
- unlisted result: compile error
basics
~20 sResults<T1, ..., T6> is a sealed union of two to six IResult types: each listed type converts to it implicitly, it executes whichever result was returned, and it merges every member's metadata, so 200, 404 and 409 are all documented.
solid answer
~40 s`Results<TResult1, TResult2>` up to `Results<TResult1, ..., TResult6>` live in `Microsoft.AspNetCore.Http.HttpResults`, and each type argument is constrained to `IResult`. The class has a private constructor and one implicit conversion per type argument, so `return TypedResults.NotFound();` compiles in a handler declared as `Results<Ok<ReturnLabel>, NotFound, Conflict<string>>`, while returning a type that is not listed does not. At run time it holds the active result in its `Result` property and its `ExecuteAsync` simply executes that result. When the endpoint is built, its `PopulateMetadata` calls `PopulateMetadata` on every type argument, so the endpoint documents 200 with `ReturnLabel`, 404 and 409 with `string`. Its limits: at most six types, a lambda must declare the union as its return type (or `Task<...>` when async), and an `IResult` from `Results.*` cannot be returned through it.
go deeper
Know that Results<A, B> lets one handler return either of two typed results, such as Ok<T> or NotFound.
Explain the implicit conversions, the metadata merge, the six-type limit, and why Results.* helpers cannot be returned through the union.
Use the union as a compile-time contract check, and redesign endpoints that push against six outcomes instead of reverting to IResult.
Decide how strictly endpoint outcome lists are treated as public contract and how their changes are reviewed and versioned.
## The problem the union solves An electronics retailer issues return labels: `POST /orders/{orderId}/items/{sku}/return-label` answers **200** with a label, **404** when the order or item does not exist, and **409** when the item has already been returned. With `TypedResults` each outcome has its own type (`Ok<ReturnLabel>`, `NotFound`, `Conflict<string>`), and C# cannot infer one return type for a lambda that returns all three. Falling back to `IResult` compiles but throws away the metadata. `Results<...>` gives the handler a single declared type that still carries every outcome. ```csharp app.MapPost("/orders/{orderId}/items/{sku}/return-label", async Task<Results<Ok<ReturnLabel>, NotFound, Conflict<string>>> ( int orderId, string sku, IReturnsService returns, CancellationToken ct) => { var item = await returns.FindItemAsync(orderId, sku, ct); if (item is null) return TypedResults.NotFound(); if (item.AlreadyReturned) return TypedResults.Conflict($"{sku} was returned on {item.ReturnedOn:d}"); return TypedResults.Ok(await returns.IssueLabelAsync(item, ct)); }); ``` ## How the type is built The ASP.NET Core 10 source generates five classes, `Results<T1, T2>` through `Results<T1, ..., T6>`, each `sealed` and implementing `IResult`, `INestedHttpResult` and `IEndpointMetadataProvider`: 1. **Constraint**: every type argument must implement `IResult`. 2. **Construction**: the only constructor is private. Instances come from **implicit conversion operators**, one per type argument, so `return TypedResults.NotFound();` converts silently. 3. **Execution**: the `Result` property holds the active `IResult`, and `ExecuteAsync` forwards to it. Filters and tests can read `Result` (it is the `INestedHttpResult` contract) to see what was actually returned. 4. **Metadata**: the static `PopulateMetadata` calls each type argument's `PopulateMetadata` in turn, so the endpoint gets one `ProducesResponseTypeMetadata` entry per documented outcome. ## What the compiler now checks | You write | Result | |---|---| | `return TypedResults.NotFound();` | compiles: `NotFound` is a type argument | | `return TypedResults.BadRequest();` | compile error: `BadRequest` is not listed | | `return Results.NotFound();` | compile error: it is typed `IResult`, which has no conversion | | `return new Results<...>(...)` | compile error: the constructor is private | This is the real value of the union: the declared contract and the code cannot disagree without the build failing. Adding a 422 branch forces you to add `UnprocessableEntity<T>` to the signature, which updates the documentation in the same edit. ## Limits and workarounds - **Six types at most.** There is no `Results<T1, ..., T7>`. An endpoint with more outcomes is usually doing too much; split it, or fall back to `IResult` and describe the responses explicitly. - **Lambdas need an explicit return type.** Write the union before the parameter list (C# 10 lambda return types), or use a named method or local function. - **Async handlers** declare `Task<Results<...>>`; the unwrapping for metadata is automatic. - **Order does not change behaviour.** Type-argument order only affects the order of metadata entries. - **Nesting is unnecessary.** Each member should be a concrete result type, not another union. - **Problem responses** such as `ProblemHttpResult` and `ValidationProblem` can be members like any other result. ## What the endpoint ends up describing For the return-label handler above, the merged metadata contains three response entries, which is exactly what the OpenAPI document and any client generator see: - **200** with a `ReturnLabel` body as `application/json`, from `Ok<ReturnLabel>`. - **404** with no body, from `NotFound`. - **409** with a `string` body as `application/json`, from `Conflict<string>`. Compare the same handler declared as `IResult` with `.Produces<ReturnLabel>(200).Produces(404).Produces<string>(409)`: the document is identical on the day it is written, but nothing stops a later edit from returning a 422 the document never mentions. With the union, that edit does not compile until the signature, and therefore the document, says 422. ## The common status factories | Factory | Status | Body | |---|---|---| | `TypedResults.Ok(value)` | 200 | JSON | | `TypedResults.Created(uri, value)` | 201 | JSON, `Location` set from `uri` | | `TypedResults.Accepted(uri)` | 202 | none, `Location` set | | `TypedResults.NoContent()` | 204 | none | | `TypedResults.NotFound()` | 404 | none | | `TypedResults.Conflict(error)` | 409 | JSON | ## What interviewers listen for - **Implicit conversions** plus a private constructor as the mechanism. - **Metadata merged** from every type argument. - **Compile-time enforcement** of the declared outcomes. - The **six-type ceiling** and the explicit return type on lambdas.
- How would a unit test check which outcome a Results<Ok<ReturnLabel>, NotFound, Conflict<string>> handler produced?Read the union's `Result` property, which holds the active `IResult`, and check its type: `Assert.IsType<Conflict<string>>(result.Result)`, then inspect `Value` on the concrete result. Because the union implements `INestedHttpResult`, endpoint filters can unwrap it the same way at run time.
- The endpoint needs a seventh outcome. What are the options?There is no seven-argument `Results`. Either split the endpoint so each handler has fewer outcomes, or declare `IResult` and document the responses explicitly, accepting that the compiler no longer ties the code to the contract. Often the extra outcome is a validation or problem response that can be produced in one place outside the handler instead.
A shipping counter with a fixed set of labelled chutes: a parcel can only be dropped into a chute that exists, and the sign above the counter lists every chute, so customers know all possible destinations before handing anything over. A parcel for an unlisted destination is refused at the counter, not lost later.
- Results<...> accepts any IResult at run time and only documents the listed ones.
- Returning Results.NotFound() from a Results<Ok<T>, NotFound> handler compiles because it is a NotFound.
- The first type argument of Results<...> sets the endpoint's default status code.
- A lambda's union return type can be inferred without declaring it.
- Results<...> can list as many result types as the handler needs.