C# 2.0, Closures and Anonymous Delegates
I was looking around the web about new features in C# 2.0, and I came across this article about the support for closures in C# 2.0. The article explains that the support for closures in C# 2.0 takes the form of anonymous delegates.
There are some examples of closures like this one :
public List<Employee> Managers(List<Employee> emps)
{
return emps.FindAll(
delegate(Employee e)
{
return e.IsManager;
}
);
}
Which is interesting, but less than this one :
public List<Employee> HighPaid(List<Employee > emps)
{
int threshold = 150 ;
return emps.FindAll(
delegate(Employee e)
{
return e.Salary > threshold;
}
);
}
The interesting part here is that the delegate is actually allowed to use a variable that is local to the method where it is defined. You might wonder how this is implemented by the C# compiler.
It may become even less obvious with this example :
{
return delegate(Employee e)
{
return e.Salary > amount;
};
}
Ok, where does the compiler stores the value of "amount" since the delegate method is only returned to be executed later... ?
In fact, the compiler only generates a "DisplayClass" that containts amount as a field initialized when the anonymous delegate is created, and the implementation of the delegate itself.
Easy.