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

            // 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,152 – The Action Delegate Type

The .NET Framework includes the Action predefined delegate type that represents the signature of a method that accepts zero or more parameters and does not have a return value (i.e. returns void).

Overloads of Action are :

  • delegate void Action()
  • delegate void Action(T p1)
  • delegate void Action(T1 p1, T2 p2)
  • etc…

You might define your own delegate type:

        public delegate void Merger<T1,T2>(T1 thing1, T2 thing2);

        static void MergeIntAndString<T1,T2>(Merger<T1,T2> myMerger, T1 n, T2 s)
        {
            myMerger(n, s);
        }

        public static void ConcatIntString(int n, string s)
        {
            Console.WriteLine("{0}{1}", n, s);
        }

        static void Main(string[] args)
        {
            MergeIntAndString(ConcatIntString, 42, "Adams");
        }

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

        static void MergeIntAndString<T1,T2>(Action<T1,T2> myMerger, T1 n, T2 s)
        {
            myMerger(n, s);
        }