Monday, January 11, 2010

Events with anonymous delegate

I subscribed to an event with an anonymous delegate. Later I was in need for a solution to be able to unsubscribe this delegate. This is a simple solution for the problem:

public class ClassName
{
    MouseButtonEventHandler eventHandler;
 
    public ClassName()
    {
        eventHandler = delegate
                                        {
                                            // operations
                                        };
    }
 
    void Functionality()
    {
        if (_subscribe)
        {
            _object.MouseLeftButtonDown += eventHandler;
        }
        else
        {
            _object.MouseLeftButtonDown -= eventHandler;
        }
    }
}

No comments:

Post a Comment