Search code examples
c#inheritancemvvmobject-composition

Composition instead of inheritance


I'm developing a WPF with MVVM pattern, .NET Framework 4.6.1. and C#.

My question is not about WPF, it's about using composition instead of inheritance with these two classes:

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChangedEvent(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

And:

public class MainViewModel : ObservableObject
{
    private string statusPrinter;

    public string StatusPrinter
    {
        get { return statusPrinter; }
        set
        {
            statusPrinter = value;
            RaisePropertyChangedEvent("StatusPrinter");
        }
    }
}

MainViewModel inheritance from ObservableObject and I don't want to use inheritance.

I can do this:

public class MainViewModel
{
    private string statusPrinter;
    private ObservableObject observable;

    public string StatusPrinter
    {
        get { return statusPrinter; }
        set
        {
            statusPrinter = value;
            observable.RaisePropertyChangedEvent("StatusPrinter");
        }
    }

    public MainViewModel()
    {
        observable = new ObservableObject();
    }
}

But it seems to be a problem with public event PropertyChangedEventHandler PropertyChanged; in ObservableObject when I use composition. The problem is when XAML link.

Can I use composition here or do I have to use inheritance?


Solution

  • You cannot use composition here, at least not in a way you presented. When something wants to subscribe to notifications for property changes for your MainViewModel object - it will first check if MainViewModel implements INotifyPropertyChanged. It does not in your case - so it cannot notify anyone about property changes.

    If you don't like to inherit from ObservableObject - don't. Just implement INotifyPropertyChanged in MainViewModel, there is nothing wrong with it.