Using Closures to Improve API Design and Usage
Some APIs such as those that perform complex parsing often expose intermediate results via events. For example, the XDocument.Validate extension method uses an event to notify the program that there are validation errors.
In traditional .NET programming, catching these events would mean creating a separate function for each event. Since there is no direct way to pass additional information into or out of the event handler, these functions are normally implemented inside a throwaway class.
Eric White uses closures to demonstrate a better way. A closure is a special case of the lambda or anonymous inline function. What makes a closure special is that can reference variables that are not local to it, but are local to the function that contains the lambda. This allows Eric to keep the event handling logic local to the function. The below line shows the closure being created and passed to the Validate function:
snippet.Validate(schemas, (o, e) => errors += e.Message + Environment.NewLine);
As a side note, closures in C# and VB are implemented as anonymous classes that contain the necessary member variables. The "enclosed" variables are moved to the new class and referenced by both the original function and any anonymous functions it contains.
Thanks for bringing attention to this language feature
Interestingly, async programming benefits greatly from closures - as evidenced by the popularity of AJAX. Closure support in the DLR helps Silverlight programs immensely because all server-side calls are handled asynchronously out of the box.
Iordanis Giannakakis, Savvas Dalkitsis Aug 28, 2015
Ben Linders Aug 28, 2015