Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous delegate closure (or why does this work)?

Tags:

c#

.net-4.0

The code below is taken directly from the sample project accompanying the article on MSDN introducing MVVM design pattern. I do not quite understand why the delegate sees the value of 'handler' other than null. My understanding was that the closure created for the delegate method contains all variables in scope that have been initialized up to this point in the execution, and since 'handler' is reassigned after the delegate is created the closure will contain 'handler' set to null.

Konstantin


EventHandler handler = null;
handler = delegate
{
    viewModel.RequestClose -= handler;
    window.Close();
};
viewModel.RequestClose += handler;
like image 470
akonsu Avatar asked May 13 '26 19:05

akonsu


1 Answers

The delegate captures the variable handler, not the contents of the variable.


It becomes more clear when you look at what the C# compiler compiles your code to, e.g., using Reflector. Your code is compiled roughly to this:

class MyAnonymousDelegate
{
    public ... viewModel;
    public ... window;
    public EventHandler handler;

    public void DoIt(object sender, EventArgs e)
    {
        this.viewModel.RequestClose -= this.handler;
        this.window.Close();
    }
}

var mad = new MyAnonymousDelegate();
mad.viewModel = viewModel;
mad.window = window;
mad.handler = null;

mad.handler = new EventHandler(mad.DoIt);

viewModel.RequestClose += mad.handler;
like image 179
dtb Avatar answered May 16 '26 11:05

dtb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!