Explanation on closures

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sjoshi23@yahoo.com

    Explanation on closures

    Hi All

    Can someone clarify what is happening in these 2 code fragments ?

    int i=0;

    Action b = delegate {i++; Console.WriteLi ne("Within b() i= +
    i.ToString());} ;

    Action<inta = delegate(int j){ j++; Console.WriteLi ne("Within a(i) =
    " + j.ToString());} ;

    i++;
    b();
    // i now becomes 2

    a(i);
    // i is reported as 3 within a

    Console.WriteLi ne("i = " + i.ToString());
    // i still shows as 2 ****

    So the question is why i changes for b and not for a ?

    thanks
    Sunit
  • Jon Skeet [C# MVP]

    #2
    Re: Explanation on closures

    <sjoshi23@yahoo .comwrote:
    Can someone clarify what is happening in these 2 code fragments ?
    >
    int i=0;
    >
    Action b = delegate {i++; Console.WriteLi ne("Within b() i= +
    i.ToString());} ;
    >
    Action<inta = delegate(int j){ j++; Console.WriteLi ne("Within a(i) =
    " + j.ToString());} ;
    >
    i++;
    b();
    // i now becomes 2
    >
    a(i);
    // i is reported as 3 within a
    >
    Console.WriteLi ne("i = " + i.ToString());
    // i still shows as 2 ****
    >
    So the question is why i changes for b and not for a ?
    The delegate created for b *captures* the i variable - in other words,
    it can still make changes to it, and see changes in the rest of the
    method.

    The delegate created for a doesn't capture any local variables -
    instead, a value is passed in as a parameter (just as it would be for
    any normal method). Incrementing that parameter value doesn't change
    the original variable's value.

    --
    Jon Skeet - <skeet@pobox.co m>
    Web site: http://www.pobox.com/~skeet
    Blog: http://www.msmvps.com/jon.skeet
    C# in Depth: http://csharpindepth.com

    Comment

    Working...