#1,167 – Passing a Lambda Expression to a Method
August 25, 2014 1 Comment
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 });