What happens if I call the handler of an event declared inside a function that is not executing?

Something like that:

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

And then SomeEvent is called after the execution of SomeFunc. I really tested it, and it worked, but cannot understand why. I thought InsideVar would be on the stack and stop after the function was executed. I was expecting an exception. Can someone please clarify this?

+3
source share
1 answer

You just discovered closures .

+4
source

Source: https://habr.com/ru/post/1752132/


All Articles