Why do closures exist for anonymous methods? Why not just pass state into the method without the overhead of a new class being generated with the closure variables being copied in? Isn’t this just a throwback to “making everything global?”
Someone talk me down, I feel like i’m missing something here…
Purely, convenience… you don’t know how much state you are going to need when defining, for example, a
Predicate<T>– consider:here we’ve passed two additional bits of state into
Predicate<T>(minandmax) – but we can’t defineList<T>.FindAll(Predicate<T>)to know about that, as that is a caller detail.The alternative is to write the classes ourselves, but that is hard, even if we are lazy:
I don’t know about you, but I prefer the version with the closure… especially when you consider how complex it gets when you have multiple contextual levels. I want the compiler to worry about it.
Consider also how often you use such constructs, especially for things like LINQ: you wouldn’t want to have to do it any other way…