Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is so special about closures?
    primarykey
    data
    text
    <p>I've been <a href="http://www.devsource.com/c/a/Languages/Cigars-Lambda-Expressions-and-NET/1/" rel="nofollow noreferrer">reading this article about closures</a> in which they say:</p> <ul> <li>"all the plumbing is automatic"</li> <li>the compiler "creates a wrapper class" and "extends the life of the variables"</li> <li>"you can use local variables without worry"</li> <li>the .NET compiler takes care of the plumbing for you, etc.</li> </ul> <p>So I made an example based on their code and to me, it seems as though closures just act similarly to regular named methods which also "take care of the local variables without worry" and in which "all the plumbing is automatic". </p> <p><strong>Or what problem did this "wrapping of local variables" solve that makes closures so special / interesting / useful?</strong></p> <pre><code>using System; namespace TestingLambda2872 { class Program { static void Main(string[] args) { Func&lt;int, int&gt; AddToIt = AddToItClosure(); Console.WriteLine("the result is {0}", AddToIt(3)); //returns 30 Console.ReadLine(); } public static Func&lt;int, int&gt; AddToItClosure() { int a = 27; Func&lt;int, int&gt; func = s =&gt; s + a; return func; } } } </code></pre> <h1>Answer</h1> <p>So the answer to this one is to read <a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx" rel="nofollow noreferrer">Jon Skeet's article on closures</a> that Marc pointed out. This article not only shows the evolution leading up to lambda expressions in C# but also shows how closures are dealt with in Java, an excellent read for this topic.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload