Search code examples
c#c#-4.0closuresanonymous-methods

Unsubscribing events in case variable closure


I'm always try to unsubscribe events where it possible and may. In case when variable closure happen I do the following:

int someVar;

EventHandler moveCompleted = null;
moveCompleted = delegate(object sender, EventArgs e)
{
    //...
    //here is variable closure
    someVar = 5;
    //...
    moveStoryboard.Completed -= moveCompleted;
};

moveStoryboard.Completed += moveCompleted;

But I don't want to use anonymous method and I think this is not good way. Please give me some advice or code samples.

Thanks in advance.


Solution

  • whats wrong with:

    class MyClass
    {
        public event EventHandler MyEvent;
    
        public MyClass()
        {
            MyEvent += OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
        }
    
        protected void OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice(object sender, EventArgs e)
        {
            MyEvent -= OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
        }
    }