tags:

views:

58

answers:

2

Something like this:

    void SomeFunc()
    {
        int InsideVar = 1;
        EventHandler handler = (s, e) => { MessageBox.Show(InsideVar.ToString()); };
        SomeEvent += handler;
    }

And then SomeEvent is invoked after SomeFunc is executed. I actually tested it and it worked but cannot understed why. I thought InsideVar would be on the stack and would stop existing after the function is executed. I was expecting an exception. Can someone clarify this please?

+3  A: 

You've just discovered closures.

anthony
+1  A: 

While not an exact duplicate, this question will tell you all you need to know:

http://stackoverflow.com/questions/428617/what-are-closures-in-net

spender