Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading