Search code examples
c#lambdac#-8.0switch-expression

Use lambda function in new switch c# 8.0 to return value


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?


Solution

  • 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();