title: Using IDisposable to unsubscribe events
body: <p>I have a class that handles events from a WinForms control. Based on what the user is doing, I am deferencing one instance of the class and creating a new one to handle the same event. I need to unsubscribe the old instance from the event first - easy enough. I'd like to do this in a non-proprietary manner if possible, and it seems like this is a job for IDisposable. However, most documentation recommends IDisposable only when using unmanaged resources, which does not apply here.</p>
  
  <p>If I implement IDisposable and unsubscribe from the event in Dispose(), am I perverting its intention? Should I instead provide an Unsubscribe() function and call that?</p>
  
  <hr>
  
  <p><strong>Edit:</strong> Here's some dummy code that kind of shows what I'm doing (using IDisposable). My actual implementation is related to some proprietary data binding (long story).</p>
  
  <pre><code>class EventListener : IDisposable
  {
      private TextBox m_textBox;
  
      public EventListener(TextBox textBox)
      {
          m_textBox = textBox;
          textBox.TextChanged += new EventHandler(textBox_TextChanged);
      }
  
      void textBox_TextChanged(object sender, EventArgs e)
      {
          // do something
      }
  
      public void Dispose()
      {
          m_textBox.TextChanged -= new EventHandler(textBox_TextChanged);
      }
  }
  
  class MyClass
  {
      EventListener m_eventListener = null;
      TextBox m_textBox = new TextBox();
  
      void SetEventListener()
      {
          if (m_eventListener != null) m_eventListener.Dispose();
          m_eventListener = new EventListener(m_textBox);
      }
  }
  </code></pre>
  
  <p>In the actual code, the "EventListener" class is more involved, and each instance is uniquely significant. I use these in a collection, and create/destroy them as the user clicks around.</p>
  
  <hr>
  
  <p><strong>Conclusion</strong></p>
  
  <p>I'm accepting <a href="https://stackoverflow.com/questions/452281/using-idisposable-to-unsubscribe-events#452321">gbjbaanb's answer</a>, at least for now. I feel that the benefit of using a familiar interface outweighs any possible downside of using it where no unmanaged code is involved (how would a user of this object even know that?).</p>
  
  <p>If anyone disagrees - please post/comment/edit. If a better argument can be made against IDisposable, then I'll change the accepted answer.</p>