Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class implements INotifyPropertyChanged : can derived types use its PropertyChanged event?

EDIT

From posters hints, I've found the following helpful links on MSDN:

How to: Raise Base Class Events in Derived Classes (C# Programming Guide)

Derived classes cannot raise base class events


While refactoring I've come across an interesting question for which I haven't found an answer so far :

The refactoring consists of creating an abstract base class which implements INotifyPropertyChanged, derived types would use it instead of implementing the interface themselves.

Can derived types use the base class event PropertyChanged or must they override it as shown below ?

If they must override it can you explain the reasons why it should be that way ?

(note: refactoring has been suggested by Resharper)

public abstract class BaseDTO : INotifyPropertyChanged
{
    public virtual event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class ReviewDTO : BaseDTO
{
    private ImageSource _image;
    private string _summary;
    private string _url;

    public string Url
    {
        get { return _url; }
        set
        {
            if (value == _url) return;
            _url = value;
            OnPropertyChanged();
        }
    }

    public string Summary
    {
        get { return _summary; }
        set
        {
            if (value == _summary) return;
            _summary = value;
            OnPropertyChanged();
        }
    }

    public ImageSource Image
    {
        get { return _image; }
        set
        {
            if (Equals(value, _image)) return;
            _image = value;
            OnPropertyChanged();
        }
    }

    public override event PropertyChangedEventHandler PropertyChanged;
}
like image 923
aybe Avatar asked Oct 22 '13 15:10

aybe


1 Answers

I don't think they must override.

The base type can define a

protected void RaisePropertyChanged(string propertyName);

The derived classes can just invoke the base method to trigger property notifications.

Just found some supporting evidence: MSDN page on implementing INotifyPropertyChanged

Of course, your base type can add more goodies

  • like creating only one instance of event args per unique property name (less junk objects)
  • inferring the name of the property via CallerMemberName
  • using lambda expression form to flag incorrect property names
like image 57
Gishu Avatar answered Sep 20 '22 20:09

Gishu