What are closures and what is their use?

Asked

Viewed 358 times

10

1 answer

11


Concept

Closure (or in Portuguese, enclosure) is a function that references free variables in the lexical context (I took it from this article on Wikipedia). That is, it is a function that references, for example, variables that are not declared in its body.

Usually 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 an enclosure, which references the variable id stated in the body of FindById (another function).

An enclosure can be assigned to a variable:

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

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

acao();

Utilizing

Suppose I use the method Distinct() implemented in IEnumerable that requires that a class of comparison be written for him 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 long. With an enclosure, I can use not the Distinct, but a more or less like class extension:

public List<Fruta> AcharMinhaFruta(Fruta fruta) 
{
    return minhasFrutas.Select(f => delegate (f) { return f.Nome == fruta.Nome; } ).ToList();
}
  • Is there any relation of Closure and Expression Trees? Should I open another question to what Expression Trees are, or these are interconnected with closure, in fact?

  • 1

    @Vinicius Expression Trees are other things. Better open another question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.