GurdeepS
GurdeepS

Reputation: 67283

Scenarios when to use closures

I've played with closures a bit in C# and even written them in production-spec apps, however, nothing has really shouted at me that this problem must be, or can only be, solved with the use of a closure.

Is there any problem where closures are particularly useful for solving? Also, is there any gotcha with closures in C# 4.0?

Thanks

Upvotes: 3

Views: 411

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503899

Given that closures are a compiler feature rather than a platform feature, there's nothing which can't be done with them.

You can write all the code which the compiler uses by hand (well, with a few exceptions when it comes to expression trees, and the compiler has access to some IL instructions which aren't exposed by the language).

However, you'd be mad not to use closures in LINQ where you need access to the enclosing variables. For example:

public List<Person> FilterByAge(IEnumerable<Person> people, int age)
{
    return people.Where(p => p.Age >= age).ToList();
}

That lambda expression is a closure, accessing age from within a delegate.

As for gotchas:

Upvotes: 6

Related Questions