#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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: Dew Drop – September 2, 2014 (#1846) | 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: