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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With