KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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. 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? Edit: 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). 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); } } 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. Conclusion I'm accepting gbjbaanb's answer , at least for now. I feel that the benefi
Tags (comma-separated)
Save Edits
Cancel