#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.

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

            TransformAndReport(
                (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 });

1167-001

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 comment