Search code examples
c#c#-3.0closuresanonymous-methodsanonymous

Closures for anonymous methods in C# 3.0


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...


Solution

  • Purely, convenience... you don't know how much state you are going to need when defining, for example, a Predicate<T> - consider:

    List<int> data = new List<int> {1,2,3,4,5,6,7,8,9,10};
    int min = int.Parse(Console.ReadLine()), max = int.Parse(Console.ReadLine());
    List<int> filtered = data.FindAll(i => i >= min && i <= max);
    

    here we've passed two additional bits of state into Predicate<T> (min and max) - but we can't define List<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:

    class Finder {
        public int min, max;
        public bool CheckItem(int i) { return i >= min && i <= max;}
    }
    ...
    Finder finder = new Finder();
    finder.min = int.Parse(Console.ReadLine());
    finder.max = int.Parse(Console.ReadLine());
    List<int> filtered = data.FindAll(finder.CheckItem);
    

    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...