#1,165 – Lambda Expression Basics

A lambda expression is an unnamed method that appears in-line in the code where it used.  It can be used wherever your code expects an instance of a delegate.

Below, the lambda expression takes the place of a method name in assigning a value to a delegate instance.  The in-line expression behaves exactly as the method does, returning a string constructed from two input parameters (int and double).

In either case, we can invoke the code (named method or lambda expression) by invoking the delegate instance and passing it the input parameters.

        delegate string IntDoubleDelegate(int i, double d);

        static void Main(string[] args)
        {
            // Method #1 - set delegate instance
            // to named method.
            IntDoubleDelegate del1 = IntDoubleInfo;
            string info1 = del1(5, 12.3);

            // Method #2 - use lambda expression
            IntDoubleDelegate del2 = (i, d) => string.Format("I:{0}, D:{1}", i, d);
            string info2 = del2(5, 12.3);
        }

        static string IntDoubleInfo(int i, double d)
        {
            return string.Format("I:{0}, D:{1}", i, d);
        }
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.

3 Responses to #1,165 – Lambda Expression Basics

  1. Pingback: Dew Drop – August 21, 2014 (#1839) | Morning Dew

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: