Search code examples
c#anonymous-methods

How to avoid anonymous methods in "dynamic" event subscription?


How could I refactor the method

private void ListenToPropertyChangedEvent(INotifyPropertyChanged source,
                                          string propertyName)
{
    source.PropertyChanged += (o, e) =>
    {
        if (e.PropertyName == propertyName)
            MyMagicMethod();
    };
}

if I wished to avoid using the anonymous method here?


Solution

  • Implement the closure that is implicitly created by the lambda explicitly:

    private void ListenToPropertyChangedEvent(INotifyPropertyChanged source,
                                              string propertyName)
    {
        var listener = new MyPropertyChangedListener(propertyName);
        source.PropertyChanged += listener.Handle;
    }
    
    class MyPropertyChangedListener
    {
        private readonly string propertyName;
    
        public MyPropertyChangedListener(string propertyName)
        {
            this.propertyName = propertyName;
        }
    
        public void Handle(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == this.propertyName)
            {
                // do something
            }
        }
    }