81

Duplicate

Closures in .NET

What are closures in C#?

Community
  • 1
  • 1
Shane Scott
  • 1,583
  • 2
  • 13
  • 11
  • Duplicate: http://stackoverflow.com/questions/428617/closures-in-net – Adam Lassek Feb 27 '09 at 16:31
  • 4
    Duplicate maybe; the accepted answer though is particularly succinct. – Roja Buck Nov 13 '11 at 23:27
  • 1
    Any practical examples available for usage of closures? – Alex Gordon Feb 19 '17 at 21:58
  • 2
    After I read "*A closure is a function that captures the bindings of free variables in its lexical context*" and only understood the word '*function*' in the sentence, I was very happy to find [Justin Etheredge article](https://www.simplethread.com/c-closures-explained/) whom author deserves a prize for explaining this using a simple and funny wording. – mins Jun 15 '19 at 12:29

1 Answers1

116

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);
Nick Bull
  • 9,518
  • 6
  • 36
  • 58
cgreeno
  • 31,943
  • 7
  • 66
  • 87