views:

146

answers:

1

basically I want to do something like this:

public static void OnPropertyChanged(this INotifyPropertyChanged changedObject, string propertyName)
{
    var handler = changedObject.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(changedObject, e);
    }
}

which gives "System.ComponentModel.INotifyPropertyChanged.PropertyChanged can only be used on the left-hand side of += or -="

I mean I can work around it by doing this:

public static void RaisePropertyChanged(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(sender, e);
    }
}

but the calling code doesn't look quite as nice:

PropertyChanged.RaisePropertyChanged(this, "Name");

vs this:

this.OnPropertyChanged("Name");

Not a big deal, but it'd be nice to be able to call it as if it was an instance method.

+1  A: 

It's also against the guidelines: On* methods in general are meant to do things based on something which INSIDE the implementing instance. In general these methods are virtual so you can override them in derived classes. Having an On* method externally therefore makes no sense. If you want to raise an event without having the dreaded null-test all over the place you indeed should use a RaiseEvent() extension method. I wrote a lot of these, all having overloads so you can just have RaiseEvent(... ) and you don't have to include the name of the event in the method. This is particularly easy in cases where you for example use the normal EventHandler type, so you can use the same extension method for more events.

Frans Bouma
Yeah, it's not really a big deal, but it didn't seem DRY to have to write that method on every class when it's just the same thing, even if it is a 1-liner.
Davy8