#1,172 – Lambda Expressions Often Used with Func and Action

Lambda expressions are quite often used with the Func and Action delegate types.  Func<> accepts zero or more parameters and returns a result.  Action<> accepts zero or more parameters and returns void.

Below are examples of lambda expressions using these delegate types.

            // Function: no parameters, returns int
            Func<int> dayOfYear = () => DateTime.Now.DayOfYear;
            int doy = dayOfYear();

            // Function: 2 parameters, returns string
            Func<int, double, string> intDoubleAdder =
                (int i, double d) =>
                    double result = i + d;
                    return string.Format("Result is {0}", result);
            string answer = intDoubleAdder(5, 4.2);

            // Action: no parameters
            Action todayReporter = () =>
                Console.WriteLine(string.Format("Today is {0}", DateTime.Today.ToLongDateString()));

            // Action: 3 parameters
            Action<string,int,double> goofyDel =
                (s, i, d) => Console.WriteLine(string.Format(s,i,d));
            goofyDel("Int is {0}, Double is {1}", 5, 12.2);

#1,151 – The Func Delegate Type

The .NET Framework includes the Func predefined delegate type, which represents the signature of a method that returns some type and accepts zero or more parameters.

Overloads of Func are :

  • delegate TResult Func<out TResult>()
  • delegate TResult Func<in T, out TResult>(T p1)
  • delegate TResult Func<in T1, in T2, out TResutl>(T1 p1, T2 p2)
  • etc…

You might define your own delegate type:

        public delegate T Merger<T>(T thing1, T thing2);

        static void MergeSomething<T>(Merger<T> someMerger, T thing1, T thing2)
            T result = someMerger(thing1, thing2);

However, you could instead use the Func delegate type, avoiding the definition of your own custom delegate type.

        static void MergeSomething2<T>(Func<T, T, T> someMerger, T thing1, T thing2)
            T result = someMerger(thing1, thing2);

Func<T,T,T> indicates that we’ll pass in a function that takes two parameters of a given type and returns a value of the same type.