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: