Can a C# lambda expression have more than one statement?

后端 未结 8 1241
花落未央
花落未央 2020-11-29 03:37

Can a C# lambda expression include more than one statement?

(Edit: As referenced in several of the answers below, this question originally asked about \"lines\" rath

8条回答
  •  余生分开走
    2020-11-29 04:26

    Let say you have a class:

        public class Point
        {
            public int X { get; set; }
            public int Y { get; set; }
        }
    

    With the C# 7.0 inside this class you can do it even without curly brackets:

    Action action = (x, y) => (_, _) = (X += x, Y += y);
    

    and

    Action action = (x, y) => _ = (X += x, Y += y);
    

    would be the same as:

    Action action = (x, y) => { X += x; Y += y; };
    

    This also might be helpful if you need to write the a regular method or constructor in one line or when you need more then one statement/expression to be packed into one expression:

    public void Action(int x, int y) => (_, _) = (X += x, Y += y);
    

    or

    public void Action(int x, int y) => _ = (X += x, Y += y);
    

    or

    public void Action(int x, int y) => (X, Y) = (X + x, Y + y);
    

    More about deconstruction of tuples in the documentation.

提交回复
热议问题