4

I want to use new switch in my code, that for method result make log and return IActionResult.

I try to do something like this:

var response = (this._coreRepository.Write(value.Content, data.Id.ToString())); \\return bool
return response switch
{
   true => () =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   },
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
};

But compiler says to me cannot convert lambda expression to type 'IActionResult' because it is not a delegate type.

How can I fix it?

Iliar Turdushev
  • 4,935
  • 1
  • 10
  • 23
Claus Stolz
  • 358
  • 4
  • 18

1 Answers1

8

The problem is that your switch expression returns a lambda expression but the containing method expects IActionResult. To fix the problem you should rewrite the return statement to immediately invoke result of the switch expression:

var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));

return (response switch
{
   // Here we cast lambda expression to Func<IActionResult> so that compiler
   // can define the type of the switch expression as Func<IActionResult>.
   true => (Func<IActionResult>) (() =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   }),
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
})(); // () - here we invoke Func<IActionResult>, the result of the switch expression.

If I were you I would rewrite this code the next way to make it easier to read:

var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));

// Now additional braces or casts are not required.
Func<IActionResult> func = response switch
{
   true => () =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   },
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
}

return func();
Community
  • 1
  • 1
Iliar Turdushev
  • 4,935
  • 1
  • 10
  • 23