Megrez7
Megrez7

Reputation: 1457

Azure Function return object type casting

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:

  1. Why there is type casting used for OkObjectResult while not for BadRequestObjectResult?
  2. Why we even need to cast for OkObjectResult?

Upvotes: 1

Views: 323

Answers (1)

Byron Jones
Byron Jones

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

Related Questions