Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are 'closures' in C#? [duplicate]

Tags:

closures

c#

Duplicate

Closures in .NET

What are closures in C#?

like image 859
Shane Scott Avatar asked Feb 27 '09 16:02

Shane Scott


People also ask

Which are closures?

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.

What are closures used for?

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.

What are closures in programming?

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.

What is a closure in simple terms?

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.


1 Answers

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); 
like image 139
cgreeno Avatar answered Sep 27 '22 19:09

cgreeno