Skip Navigation LinksHome > View Post

Func and Action

In the previous post we looked at delegates and lambda expressions and promised to revisit the following example lambda:

strings.Where(x => x.StartsWith("b"));

Let's flesh this out a little bit so we can see the strings array being created and the result of this lambda being assigned to a local anonymous type.

string[] strings = { "barrier", "octopus", "carrot", "banana", "monkey" };
var beginsWithB = strings.Where(x => x.StartsWith("b"));

We can then iterate over each string in beginsWithB to prove that our Where lambda has selected only the strings beginning with 'b':

barrier and banana in console window

Well it works, but what is it doing?

If we take a look at the Where() extension method on our string array we'll see it has the following signature:

Where(Func<string, bool> predicate)

The predicate parameter is a delegate method that takes one parameter of type string and returns a bool. This is indicated by the Generic type Func which has a number of generic overloads:

Func<TResult>
Func<T1, TResult>
Func<T1, T2, TResult>
Func<T1, T2, T3, TResult>
Func<T1, T2, T3, T4, TResult>

These are just generic (in the true sense of the word) delegates where T1 through T4 represent the types of parameters the method accepts and TResult represents the return type.

So, in light of this our lambda makes more sense...

x => x.StartsWith("b")

The type x is a string parameter and x.StartsWith("b") returns a bool so the signature requirements are satisfied. Note how we don't even have to specify return?

Just to prove the point a little further, here's the same code using a C# 2.0 anonymous delegate:

var beginsWithB = strings.Where(delegate(string str) { return str.StartsWith("b"); });

Neat - but I wouldn't recommend it :).

Oh yes, I forgot to mention the Action<> generic type which is similar to Func<> but for delegates with a void return type. So how would I write a lambda that takes no parameters and returns void?

Action writeDateTime = () => Console.WriteLine(DateTime.Now);
writeDateTime();

Hello world in lambda ;)

Easy peasy.

Tags: C#

 
Josh Post By Josh Twist
1:11 AM
19 May 2008

» Next Post: Updated Silverlight Uploader for SL2 Beta 1
« Previous Post: Delegates and Lambda

Comments are closed for this post.

Posted by Andrew Zhu @ 03 Sep 2010 6:41 AM
good article, thanks

© 2005 - 2014 Josh Twist - All Rights Reserved.