title: Attach event handler to be called only once
body: <p>I am currently trying to write an extension function to be able to easily attach an action that is only used once when the event is fired, then unsubscribed.</p>
  
  <p>I am trying something like this:</p>
  
  <pre><code>public static void AttachOnce&lt;TEventArgs&gt;([NotNull] this EventHandler&lt;TEventArgs&gt; me, [NotNull] Action&lt;object, TEventArgs&gt; action)
      where TEventArgs : System.EventArgs
  {
      var handler = me;
      EventHandler&lt;TEventArgs&gt; wrappedAction = null;
      wrappedAction = (sender, args) =&gt;
      {
          action(sender, args);
          handler -= wrappedAction;
      };
      handler += wrappedAction;
  }
  </code></pre>
  
  <p>But ReSharper complains on the unsubscribe that <code>handler</code> is <strong>"Access to modified closure"</strong>.</p>
  
  <p>I know what this means, so I made the local variable for the closure already, but it doesn't seem to resolve it. What is failing here?</p>
  
  <p>The direct hard-coded code works. Something like this:</p>
  
  <pre><code>var file = new FileSystemWatcher("path/to/file");
  
  FileSystemEventHandler handler = null;
  handler = (sender, args) =&gt;
  {
      // My action code here
      file.Changed -= handler;
  };
  file.Changed += handler;
  </code></pre>
  
  <h3>EDIT 1 (2018-10-09 11:43 CET):</h3>
  
  <p>I may just have been too fast, asking a question before thoroughly thinking it through.<br>
  You can't create extension methods on Events. At all. It's just not possible in C#. So I can't even test why ReSharper is complaining and if it is right, because a call like <code>file.Changed.AttachOnce(action)</code> is not valid. It says <strong>"The event 'Changed' can only appear on the left hand side of += or -="</strong>.</p>
  
  <p>I have found some more sources for similar requests/questions:<br>
  <a href="http://www.hardkoded.com/blog/csharp-wishlist-extension-for-events" rel="nofollow noreferrer">http://www.hardkoded.com/blog/csharp-wishlist-extension-for-events</a><br>
  <a href="https://stackoverflow.com/questions/27766873/one-time-generic-event-call">One time generic event call?</a></p>