Home Using ternary operator with return
Reply: 2

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#
benjrb Reply to 2018-02-14 10:27:27Z

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();
nvoigt
3#
nvoigt Reply to 2018-02-14 10:40:07Z

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();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.351884 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO