C# switch in lambda expression

Viewed 31856

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

7 Answers

You can in a statement block lambda:

public static string CarBrandIdNotExist(AppLanguage language) => language switch
    {
        AppLanguage.English => "CarBrandId not exist",
        AppLanguage.Arabic => "CarBrandId not exist",
        AppLanguage.India => "CarBrandId not exist",
        AppLanguage.Filipino => "CarBrandId not exist",
        _ => "CarBrandId not exist",
    };

enter image description here

I just learn this:

                      (model) =>
                                {
                                    switch(model.SentInvoiceTypeId)
                                    {
                                        case 1:
                                            return "1 asdf";
                                        case 2:
                                            return "2 asdf";
                                        case 3:
                                            return "3 asdf ";
                                        case 4:
                                            return "4 asdf ";
                                        default:
                                            return "asdf";
                                    }
                                }

Just put between the "model" () and add your code in { }, remember to have a return.
I am not sure in which versions of C# will work, In this example is the C# 7.0

I hope this answer can help someone.

Related