Home Using ternary operator with return

# Using ternary operator with return

Dear Deer
1#
Dear Deer Published in 2018-02-14 10:01:45Z
 Why I can't shortcut this : if (await query.AnyAsync()) { return new ObjectResult(query); } else { return NotFound(); }  to this : await query.AnyAsync() ? return new ObjectResult(query) : return NotFound();  How can I shortcut this ?
benjrb
2#
 You're missing a cast. To use a conditional expression you need to cast them to the same return type e.g. return await query.AnyAsync() ? (ActionResult)new ObjectResult(query) : (ActionResult)NotFound(); 
 This is not exactly what you asked for, but anyway: These lines are wrong: if (await query.AnyAsync()) { return new ObjectResult(query); }  Either your query is already materialized, in which case it makes no sense to see if it has any entries asynchronously. Thhat would be overhead plain and simple. OR it is not materialized, in which case your Any call is useless, because it will only materialize it once then check if it has entries and then materialize it again for your result. That second call might as well contain no entries if something changes in your source between those calls. Best case is it's double the runtime for the same result. So if you want to simplify and correct it: var materialized = query.ToList(); if (materialized.Count != 0) { return new ObjectResult(materialized); } return NotFound();  It does not get more simple. No need for a ternary operator here. If you want a ternary operator, you will need to make sure it gets expressions of the same type, not statements (return 0; is a statement, 0 is an expression): var materialized = query.ToList(); return (materialized.Count != 0) ? (IActionResult)new ObjectResult(materialized) : (IActionResult)NotFound();