3

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?

Juan
  • 15,274
  • 23
  • 105
  • 187
  • 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 Jun 28 '10 at 19:38

1 Answers1

4

You've just discovered closures.

anthony
  • 40,424
  • 5
  • 55
  • 128