#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: