Closures in C# (better known as lambdas)
I’m a big fan of Martin Fowler, the author of such brilliant and practical books as Refactoring: Improving the Design of Existing Code, Patterns of Enterprise Application Architecture
and UML Distilled
(these are books that every developer should have, study and refer to often). Today I was reading an article on his web site and I came across the term “Closure“. I’d come across it some years ago whilst reading another article on his site and I’d gotten a basic concept of what it meant at the time, but I never really used it, so the concept became foggy.
Today when looking over his description of what a closure is I realized the obvious: for us .NET types a closure can be accomplished with a lambda expression.
I read the full article on Martin’s site then clicked on the “C#” link at the bottom and was taken to the old blog of Joe Walnes, where he gives C# 2.0 versions of Martin’s closure examples.
I looked at them and thought how would you do these in C# 3.0? Well, I couldn’t resist the challenge, so here they are.
The main difference now between the Ruby examples and the C# examples is the type declarations in C#: you have to say what the methods return, what types their parameters are and that threshold is an int. But, notice that with the lambda expressions you don’t have to specify the type because it is inferred by the compiler.
While I was doing this I got a bit carried away and created more ways of implementing these, but to keep the emphasis 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.
| Ruby | |
| 1. |
def managers(emps)
return emps.select {|e| e.isManager}
end
|
| 2. |
def highPaid(emps)
threshold = 150
return emps.select {|e| e.salary > threshold}
end
|
| 3. |
def paidMore(amount)
return Proc.new {|e| e.salary > amount}
end
|
| 4. |
highPaid = paidMore(150) john = Employee.new john.salary = 200 print highPaid.call(john) |
| C# 3.0 | |
| 1. |
public List<Employee> Managers(List<Employee> emps) {
return emps.FindAll(e => e.IsManager);
}
|
| 2. |
public List<Employee> HighPaid(List<Employee> emps) {
int threshold = 150;
return emps.FindAll(e => e.Salary > threshold);
}
|
| 3. |
public Predicate<Employee> PaidMore(int amount) {
return e => e.Salary > amount;
}
|
| 4. |
var highPaid = PaidMore(150); var john = new Employee(); john.Salary = 200; Console.WriteLine(highPaid(john)); |
[...] 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 [...]
Fun with lambda expressions « My Software Notes
June 7, 2009 at 4:39 pm
thanks for your sharing…
Ecko
June 15, 2010 at 3:39 am