title: How can lambda expressions as event handlers can change local variables?
body: <p>I was writing some tests for one of my classes and I needed to test that an event was being raised.  Out of just trying it and seeing what happened I coded something similar to the following extremely simplified code.</p>
  
  <pre><code>public class MyEventClass
  {
      public event EventHandler MyEvent;
      public void MethodThatRaisesMyEvent()
      {
          if (MyEvent != null)
              MyEvent(this, new EventArgs());
      }
  }
  
  [TestClass]
  public class MyEventClassTest
  {
      [TestMethod]
      public void EventRaised()
      {
          bool raised = false;
          var subject = new MyEventClass();
          subject.MyEvent += (s, e) =&gt; raised = true;
  
          subject.MethodThatRaisesMyEvent();
  
          Assert.IsTrue(raised);
      }
  }
  </code></pre>
  
  <p>I wasn't so much amazed when it worked as when I started to try and figure out how it worked.  Specifically, how would I write this without lambda expressions so that the local variable <code>raised</code> can be updated?  In other words, how is the compiler refactoring/translating this?</p>
  
  <p>I got this far...</p>
  
  <pre><code>[TestClass]
  public class MyEventClassTestRefactor
  {
      private bool raised;
  
      [TestMethod]
      public void EventRaised()
      {
          raised = false;
          var subject = new MyEventClass();
          subject.MyEvent += MyEventHandler;
  
          subject.MethodThatRaisesMyEvent();
  
          Assert.IsTrue(raised);
      }
  
      private void MyEventHandler(object sender, EventArgs e)
      {
          raised = true
      }
  }
  </code></pre>
  
  <p>But this changes <code>raised</code> to a class-scoped field rather than a local-scope variable.</p>