0

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.

2 Answers2

1

If you don't want to use an anonymous function, it's much easier:

moveStoryboard.Completed += HandleStoryboardCompleted;

...

private void HandleStoryboardCompleted(object sender, EventArgs e)
{
    // Do stuff...
    moveStoryboard.Completed -= HandleStoryboardCompleted;
}

That will actually create another instance of EventHandler each time the method is called, but because that instance will be equal to the one used to subscribe (same method with the same target) it will be fine to use for unsubscription.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you Jon for your answer. It's an honor for me. But I'm interested in case when variable closure happen. –  Nov 04 '11 at 07:46
  • @Arterius: You've said you don't want to use anonymous functions, which is precisely when variables *are* captured. It's not really clear what you're trying to achieve. Do you want to use anonymous functions or not? – Jon Skeet Nov 04 '11 at 07:53
  • I thought maybe use of Dictionary may help to hold variable I need and then after using remove from Dictionary. –  Nov 04 '11 at 08:03
  • If usage of anonymous methods is precisely when variables are captured then I will continue write a code as shown in question. I just want to now is there some good practice to do same without using anonymous methods. –  Nov 04 '11 at 08:05
  • @Arterius: Well, anonymous methods and lambda expressions - both of which count as "anonymous functions". – Jon Skeet Nov 04 '11 at 08:19
1

whats wrong with:

class MyClass
{
    public event EventHandler MyEvent;

    public MyClass()
    {
        MyEvent += OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }

    protected void OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice(object sender, EventArgs e)
    {
        MyEvent -= OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }
}
Polity
  • 14,734
  • 2
  • 40
  • 40
  • In case when I have a local variable in constructor how can I use it in OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice ? –  Nov 04 '11 at 07:54
  • @Arterius - In that case, make it a class member. – Polity Nov 04 '11 at 08:15