Reputation: 1457
Trying to understand default return
code from Azure Function
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
This depending on name
value will execute:
If name
is null
:
return new BadRequestObjectResult("Please pass a name on the query string or in the request body");
Otherwise:
return (ActionResult)new OkObjectResult($"Hello, {name}")
My questions:
OkObjectResult
while not for BadRequestObjectResult
?OkObjectResult
?Upvotes: 1
Views: 323
Reputation: 745
If you did this...
if(name != null)
{
return new OkObjectResult($"Hello, {name}");
}
else
{
return new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
...casting would not be necessary.
Type casting is necessary on the line of code you have in your question because of its use of the ternary operator (i.e. a ? b : c
). When using a ternary operator, both elements after the predicate (b
and c
) must share a type in common. OkObjectResult
and BadRequestObjectResult
are two different types, so without the cast, this is unacceptable.
However, b
and c
both inherit from ActionResult
. By casting OkObjectResult
to ActionResult
, the BadRequestObjectResult
element becomes acceptable, because it too is of type ActionResult
.
Upvotes: 2