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