title: C# technique for generating anonymous delegates that share same closure variable
body: <p>I have a situation where I need to generate a few similar anonymous delegates.  Here's an example:</p>
  
  <pre><code>public void Foo(AnotherType theObj)
  {
      var shared = (SomeType)null;
  
      theObj.LoadThing += () =&gt;
      {
          if(shared == null)
              shared = LoadShared();
  
          return shared.Thing;
      };
  
      theObj.LoadOtherThing += () =&gt;
      {
          if(shared == null)
              shared = LoadShared();
  
          return shared.OtherThing;
      };
  
      // more event handlers here...
  }
  </code></pre>
  
  <p>The trouble I'm having is that my code isn't very DRY.  The contents of each of the event handlers is EXTREMELY similar, and could be easily parameterized into a factory method.  The only thing preventing me from doing that is that each delegate needs to share the reference to the <code>shared</code> variable.  I can't pass <code>shared</code> to a factory method with the <code>ref</code> keyword, as <a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.80%29.aspx" rel="nofollow noreferrer">you can't create a closure around a <code>ref</code> varaiable</a>.  Any ideas?</p>