title: C# closures and access to external variables
body: <p>I'm trying to use the following by calling: <code>StaticClass.DeleteObject(null, key)</code>. It didn't work as I expected, and the code in the lambda expression throws a NullReferenceException because context is null, which is understandable. I tried changing the context parameter of AmazonS3Operation to a ref, but ReSharper then warns of "Access to modified closure."</p>
  
  <p>Basically I'm just trying to "inject" the lambda expression in that helper method, then call it, if you get the idea of how I'd like it to work. Is this possible, or what could I do that's similar if not?</p>
  
  <pre><code>/// &lt;exception cref="IOException"&gt;&lt;/exception&gt;
  public static void DeleteObject(this AmazonS3Context context, string key)
  {
      AmazonS3Operation(context, () =&gt; context.Client.DeleteObject(
          new DeleteObjectRequest().WithBucketName(context.CurrentBucket)
              .WithKey(key)));
  }
  
  /// &lt;exception cref="IOException"&gt;&lt;/exception&gt;
  private static void AmazonS3Operation(AmazonS3Context context, Action operation)
  {
      var shouldDispose = false;
      try
      {
          if (context == null)
          {
              context = new AmazonS3Context();
              shouldDispose = true;
          }
  
          operation();
      }
      catch (AmazonS3Exception e)
      {
          throw new IOException(e.Message, e);
      }
      finally
      {
          if (shouldDispose)
              context.Dispose();
      }
  }
  </code></pre>