Search code examples
c#lambdaexpression-treesswitch-statement

C# switch in lambda expression


Is it possible to have a switch in a lambda expression? If not, why? Resharper displays it as an error.


Solution

  • You can in a statement block lambda:

    Action<int> action = x =>
    {
      switch(x)
      {
        case 0: Console.WriteLine("0"); break;
        default: Console.WriteLine("Not 0"); break;
      }
    };
    

    But you can't do it in a "single expression lambda", so this is invalid:

    // This won't work
    Expression<Func<int, int>> action = x =>
      switch(x)
      {
        case 0: return 0;
        default: return x + 1;
      };
    

    This means you can't use switch in an expression tree (at least as generated by the C# compiler; I believe .NET 4.0 at least has support for it in the libraries).