#1,167 – Passing a Lambda Expression to a Method

You can use a lambda expression anywhere that a delegate instance is expected.  This includes passing a lambda expression as a parameter to a method that takes a delegate type.

In the example below, we have a method that has two parameters that are delegate types.  It takes a transformer function that accepts and int and returns an int.  It also accepts a delegate that reports something about two different int values.

            // Transform one int to another int and report the result
            static void TransformAndReport(Func<int,int> transformer, Action<int,int> reporter, int[] data)
                foreach (int ival in data)
                    int newVal = transformer(ival);
                    reporter(ival, newVal);

We can call this method by passing in two different lambda expressions.

                (i) => i * 3,
                (inVal,outVal) => Console.WriteLine("{0} became {1}", inVal, outVal),
                new int[]{1, 2, 3});

                (i) => {
                    double cosVal = Math.Cos(i);
                    return (int)Math.Truncate((cosVal * 100) - i);
                (inVal, outVal) => Console.WriteLine("{0} yields {1}", inVal, outVal),
                new int[] { 20, 40, 60, 90 });



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

One Response to #1,167 – Passing a Lambda Expression to a Method

  1. Pingback: Dew Drop – August 25, 2014 (#1841) | 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: