C# lambda expression switch

c# expression-trees lambda switch-statement


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

8/28/2019 8:13:13 AM

Accepted Answer

You can in a statement block lambda:

Action<int> action = 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 =>
    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).

10/14/2011 11:47:11 AM

Expert Answer

In a pure Expression (in .NET 3.5), the closest you can get is a compound conditional:

    Expression<Func<int, string>> func = x =>
        x == 1 ? "abc" : (
        x == 2 ? "def" : (
        x == 3 ? "ghi" :
                 "jkl")); /// yes, this is ugly as sin...

Not fun, especially when it gets complex. If you mean a lamda expression with a statement body (only for use with LINQ-to-Objects), then anything is legal inside the braces:

    Func<int, string> func = x => {
        switch (x){
            case 1:  return "abc";
            case 2:  return "def";
            case 3:  return "ghi";
            default: return "jkl";

Of course, you might be able to outsource the work; for example, LINQ-to-SQL allows you to map a scalar UDF (at the database) to a method on the data-context (that isn't actually used) - for example:

var qry = from cust in ctx.Customers
          select new {cust.Name, CustomerType = ctx.MapType(cust.TypeFlag) };

where MapType is a UDF that does the work at the db server.

9/16/2009 1:46:16 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow