What are closures and what is their use?

10

The answer to this lambda question What are lambda expressions? And what's the point in using them? talks about closures and expressions tree, however, does not have a clear example of what they are in fact and what their main use. So what are closures and in what situation is it important to use them?

    
asked by anonymous 03.09.2014 / 22:11

1 answer

10

Concept

Closure is a function that references free variables in the lexical context ( I removed this article from Wikipedia ). That is, it is a function that references, for example, variables that are not declared in your body.

Normally closures are anonymous and exist only in the body of another method.

For example:

public Fruta FindById(int id)
{
    return this.Find(delegate(Fruta f)
    {
        return (f.Id == id);
    });
}

In this case, delegate(Fruta f) { ... } is a cloister, which references the variable id declared in the body of FindById (another function).

A cloister can be assigned to a variable:

Action acao = delegate { Console.WriteLine(umaStringQualquer); };

And activated at some specific time in the function or method:

acao();

Use

Suppose I'm going to use the Distinct() method implemented in IEnumerable that requires a comparison class to be written to it like this:

class Comparador : IEqualityComparer<Fruta>
{
    public bool Equals(Fruta x, Fruta y)
    {
        if (x.Nome == y.Nome)
        {
            return true;
        }
        else { return false; }
    }

    public int GetHashCode(Fruta fruta)
    {
        return 0;
    }
}

It works, but it's a little wordy. With a cloister, I can use not Distinct , but a class extension something like this:

public List<Fruta> AcharMinhaFruta(Fruta fruta) 
{
    return minhasFrutas.Select(f => delegate (f) { return f.Nome == fruta.Nome; } ).ToList();
}
    
03.09.2014 / 22:25