ASP.NET Core docs show unfamiliar usage of the ? operator. What does it mean?

Advertisements

The ASP.NET Core minimal API docs show syntax similar to the following:

db.Todos.Find(id)
is Todo todo
    ? Results.Ok(todo)
    : Results.NotFound());

I believe this is a use case of the ? operator which is documented in the main C# docs. However, these docs only show the following format:

condition ? consequent : alternative

in which condition must evaluate to a boolean.

The is keyword allows checking whether a particular variable has a certain type, so something like db.Todos.Find(id) is Todo should be sufficient.

However, they also introduce a variable todo, which is not being declared anywhere prior to this statement, and which they appear to pass as an argument to Results.Ok

I’m confused now. What does the addition of todo mean. Where is it documented that a variable can be included after condition? If it is not documented, then why not?

>Solution :

That’s a typesafe pattern matching cast.

So the variable ‘todo’ is verifiably a non-null Todo.

Leave a ReplyCancel reply