C# language feature:

  • Lambda expression

applies to

  • delegates, expressions trees, functions

benefit

  • 1) Allows writting of local functions that can be passed as arguments or returned as the value of function calls.
  • 2) Helpful for writing LINQ query expressions.

how to use

  • Specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side.

note

  • Input parameters may be enclosed by parentheses. For other uses of lambda notation, please see https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/statements-expressions-operators/lambda-expressions

example:

        delegate int delegate_accept_and_return_int(int i);
        delegate bool delegate_accept_int_return_bool(int i);
        void Use_of_Lambda_Expression()
        {
            delegate_accept_and_return_int getsquare = x => x * x; // define delegate using lambda expression
            int y = getsquare(5); //y = 25  

            int testvalue = 5;
            // Note delegate definition has access to outer variable testvalue.  
            delegate_accept_int_return_bool isgreaterthan = (x) => { return x > testvalue; };  //  define delegate using lambda expression
            bool result = isgreaterthan(6); // result is true
        }