Chapter 37. Closure

A block of code that can be represented as an object (or first-class data structure) and placed seamlessly into the flow of code by allowing it to reference its lexical scope.

var threshold = ComputeThreshold();var heavyTravellers = employeeList.FindAll(e => e.MilesOfCommute > threshold);

Also known as: lambda, block, or anonymous function

You have a collection of objects and want to filter them in various ways. Writing a method for each filter leads to duplication in the setup and processing of the filter.

By using a Closure, you can factor the setup and processing of the filter and pass in an arbitrary block of code for each filter condition.

37.1 How It Works

Closures are a language feature that, despite being around ...

Get Domain Specific Languages now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.