What are 'closures' in C#?

C#Closures

C# Problem Overview


Duplicate

>Closures in .NET

What are closures in C#?

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShane ScottView Question on Stackoverflow
Solution 1 - C#cgreenoView Answer on Stackoverflow