Closures in .NET
What are closures in C#?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.
A closure is a programming technique that allows variables outside of the scope of a function to be accessed. Usually, a closure is created when a function is defined in another function, allowing the inner function to access variables in the outer one.
1 : an act of closing : the condition of being closed closure of the eyelids business closures the closure of the factory. 2 : an often comforting or satisfying sense of finality victims needing closure also : something (such as a satisfying ending) that provides such a sense.
A closure in C# takes the form of an in-line delegate/anonymous method. A closure is attached to its parent method meaning that variables defined in parent's method body can be referenced from within the anonymous method. There is a great Blog Post here about it.
Example:
public Person FindById(int id) { return this.Find(delegate(Person p) { return (p.Id == id); }); }
You could also take a look at Martin Fowler or Jon Skeet blogs. I am sure you will be able to get a more "In Depth" breakdown from at least one of them....
Example for C# 6:
public Person FindById(int id) { return this.Find(p => p.Id == id); }
which is equivalent to
public Person FindById(int id) => this.Find(p => p.Id == id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With