What are 'closures' in C#?

Shane Scott picture Shane Scott · Feb 27, 2009 · Viewed 76.1k times · Source

Duplicate

Closures in .NET

What are closures in C#?

Answer

cgreeno picture cgreeno · Feb 27, 2009

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);