1

The following code is from a main window in a WPF application:

public MainWindow()
{
    ...
    Storyboard myStoryboard = new Storyboard();
    ...

    _button.Click += delegate(object sender, RoutedEventArgs args)
    {
        myStoryboard.Begin(_control);
    };
    ...
}

The object myStoryboard is defined locally within MainWindow(). Yet the unnamed delegate for the button click event is able to access this object. How is this possible? When the delegate is invoked as a result of the click event, what is its runtime environment?

(C# as provided with Visual Studio 2010, .NET 4.0.)

Sabuncu
  • 5,095
  • 5
  • 55
  • 89

1 Answers1

3

The compiler is creating an extra type which stores the local variable. Both the method and the lambda expression then use an instance of that extra type. The code would be something like this:

public MainWindow()
{
    CunningCapture capture = new CunningCapture { @this = this };
    capture.myStoryboard = new Storyboard();
    ...

    _button.Click += capture.Method;
    ...
}

private class CunningCapture
{
    public Storyboard myStoryboard;
    public MainWindow @this;

    public void Method()
    {
        myStoryboard.Begin(@this._control);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Combined w/ Sriram's comment, located the corresponding topic in section 5.5 of your book (3rd ed). Thank you so much. – Sabuncu Nov 14 '14 at 11:19
  • For those confused by `@this`, see SO question here: http://stackoverflow.com/questions/5536540/what-does-t-this-mean-in-a-delegate-declaration – Sabuncu Nov 15 '14 at 09:07