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();
}
Related: closures in Javascript :) BTW +1
– Oralista de Sistemas