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

后端 未结 8 1184
花落未央
花落未央 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

    With c# 7.0 You can use like this also

    Public string ParentMethod(int i, int x){
        int calculation = (i*x);
        (string info, int result) InternalTuppleMethod(param1, param2)
        {
            var sum = (calculation + 5);
            return ("The calculation is", sum);
        }
    }
    
    0 讨论(0)
  • 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<int, int> action = (x, y) => (_, _) = (X += x, Y += y);
    

    and

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

    would be the same as:

    Action<int, int> 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.

    0 讨论(0)
提交回复
热议问题