#1,173 – Lambda Expression Can Be Just an Expression

You’ll often see lambda expressions written as either a single statement (no return value) or a block of statements (optional return value).

        static void SomeMethod(int i, string s)
        {
            // do something with int and string
        }

        static void Main(string[] args)
        {
            // Single statement
            Action<int, string> thing1 = (i, s) => SomeMethod(i, s);

            // Block of statements, no return value
            Action<int, string> thing2 = (i, s) =>
            {
                for (int i2 = i; i2 <= i + 10; i2++)
                    SomeMethod(i2, s);
            };

            // Block of statements with return value
            Func<int,int> thing3 = (i) =>
            {
                SomeMethod(i, "x");
                return i + 1;
            };
        }

A lambda expression can also be a single statement representing an expression whose type is assignment compatible with the return value of the delegate type being assigned to.

            // Expression
            Func<int, int> doubleMe = (i) => 2 * i;
            Console.WriteLine(doubleMe(42));

1173-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: