#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);