liveBook · Manning

Ternary conditional operator

As explained in .NET in Action, Second Edition

A ternary operator is a conditional C# operator that evaluates a Boolean expression and selects one of two value expressions.

A ternary operator evaluates a Boolean expression and selects one of two values. Its compact form is <boolean expression> ? <true value> : <false value>. section 3.1.2

Selecting an HTTP result

When AsciiArt.Write returns a Boolean and both branches produce IResult values, the operator expresses success or failure directly: AsciiArt.Write(text, out var asciiText, font) ? Results.Content(asciiText!) : Results.NotFound(); The true expression returns generated content; the false expression returns HTTP 404. section 3.1.2

Listing 3.16 Returning 404 if font is invalid
app.MapGet("/{text}",
  (string text, string? font) =>
    AsciiArt.Write(text, out var asciiText, font)    #1
      ? Results.Content(asciiText!)                  #2
      : Results.NotFound());                         #3

Inspect the focused minimal-API listing showing a ternary expression selecting between Results.Content and Results.NotFound. section 3.1.2

How .NET in Action, Second Edition covers it

How deep it goes
Defines the three-part syntax and demonstrates equivalent if/else behavior, without expanding into broader operator semantics.
Examples
Demonstrates AsciiArt.Write selecting Results.Content for success and Results.NotFound for an invalid font.
What you can do after
Apply it in C# endpoints to express compact success-or-failure value selection.
How it connects
Connects Boolean expressions, if/else statements, out parameters, and ASP.NET Core IResult responses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.