#1,166 – Lambda Expression Syntax

A lambda expression is composed of:

  • A parameter list with variable names, representing 0 or more parameters
  • A lambda operator:  =>  (read as “goes to”)
  • One of
    • Single statement (no return value)
    • Block of statements with optional return statement
    • Single statement that is an expression

Below are examples of the different variants.

            // No input params
            Action del1 = () => Console.WriteLine("Hi");
            del1();

            // Single input parameter
            Action<int> del2 = i => Console.WriteLine(i);
            del2(5);

            // Multiple input parameters
            Action<int, string> del3 = (i, s) => Console.WriteLine(i.ToString() + s);
            del3(5, "Bob");

            // Input integer, return string
            Func<int, string> del4 = (i) => string.Format("Double: {0}", i * 2);
            string s2 = del4(5);
            Console.WriteLine(s2);

            // Multiple statements in body
            Action<int> del5 =
                (i) => {
                    Console.WriteLine(i);
                    double dCubed = Math.Pow(i, 3.0);
                    Console.WriteLine(dCubed);
                };
            del5(5);

            // Input parameter, return value, statement block
            Func<int, int> del6 =
                (i) =>
                {
                    int i2 = i * 10 + 12;
                    return i2;
                };
            del6(42);

1166-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment