My Software Notes

Useful things I discover

Fun with lambda expressions

with one comment

While creating C# 3.0 equivalents to the Martin Fowler example Closures in Ruby in my last post (Closures in C# (better known as lambdas)), I was having so much fun that I carried on and came up with this:

Here are the “inline” versions (the PaidMore example is my favorite – just look at the original C# 2.0 version and you’ll see how far we have come):

Example Inline C# 3.0
var managers = emps.FindAll(e => e.IsManager);
var managers = emps.Where(e => e.IsManager);
var highPaidEmps = emps.FindAll(e => e.Salary > threshold);
var highPaidEmps = emps.Where(e => e.Salary > threshold);
Func<int, Predicate<Employee>> PaidMore = amount => e => e.Salary > amount;
Using PaidMore
var highPaid = PaidMore(150);

var areHighPaid = emps.FindAll(highPaid);
var areHighPaid = emps.Where(e => highPaid(e));

(Note that “Where()” returns an anonymous type so if you wanted a List<Employee> you’d need to call the “ToList()” method.)

I also did LINQ expression versions of all the above, and whilst they are implementing lambdas in the background, you can’t see them in the code, so I didn’t include them here.

Getting a little off the subject of closures, another cool use of the C# 3.0 features is to implement PaidMore as an extension method:

public static bool PaidMore(this Employee e, int amount)
    return e.Salary > amount;

Then call it like this:

var areHighPaid = emps.Where(e => e.PaidMore(150));


var areHighPaid = from e in emps
		where e.PaidMore(150)
		select e;

Closures/Lambdas not only open up a lot of possibilities but also add a new element of fun to C# programming.


Written by gsdwriter

June 7, 2009 at 3:06 pm

Posted in Languages

Tagged with , ,

One Response

Subscribe to comments with RSS.

  1. […] While I was doing this I got a bit carried away and created more ways of implementing these, but to keep the attention on the comparison between the original Ruby closures and the .NET lambdas I will put the other versions in another post: Fun with lambda expressions. […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: