# Simplify IActionResult return value logic

It would be nice to simplify the verbosity of this:

public IActionResult Get(int id)
{
var movie = context.GetMovie(id);

if (movie != null)
{
return Ok(movie);
}
else
{
return NotFound();
}
}


with something like this:

public IActionResult Get(int id)
{
var movie = context.GetMovie(id);
return (movie != null) ? Ok(movie) : NotFound();
}


Of course, this is an error because the two objects in the ternary must be of the same type, not just sharing the same inheritance (or is this incorrect?).

The closest I can get is to explicitly cast one of the values as an IActionResult:

return (movie != null) ? Ok(movie) : (IActionResult) NotFound();


Is there a better option?

• This should be applicable to both ASP.NET and ASP.NET Core - right? – Erik Anderson Sep 1 '17 at 17:59
• Looks very readable the way it is to begin with. The if block returns so you could get rid of the else. – James Sep 2 '17 at 2:13
• The two methods both return objects that inherit from StatusCodeResult. If you use an intermediate variable like StatusCodeResult result = (movie == null) ? NotFound() : Ok(); does it work? – RubberDuck Sep 3 '17 at 1:14
• As an aside, I agree with James that the code you have is perfectly fine the way it is. It's clear and readable as is. Shorter isn't necessarily better. – RubberDuck Sep 3 '17 at 1:15

So, as mentioned in comments: the code is readable and there are no issues with "verbosity". And as mentioned you can get rid of else statement, also it's a good habit to exclude "bad" cases at first.

public IActionResult Get(int id)
{
var movie = context.GetMovie(id);

if (movie == null)
{
return NotFound();
}

return Ok(movie);
}


If Ok returns null if you pass a null as argument you can simplify it like this

public IActionResult Get(int id, Context context) => Ok(context.GetMovie(id)) ?? NotFound();

• Oh, now that's interesting! – Erik Anderson Sep 8 '17 at 16:54