I would like to avoid code duplication. Because of C#'s single inheritance, I can't just create BaseNotifyPropertyChanged class:
class BaseNotifyPropertyChanged : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Because some classes that need to implement INotifyPropertyChanged also need to inherit from other classes. And I can't make this my very base class because some classes inherit from .NET classes, and this would also pollute all classes in my solution because only some classes actually need the INotifyPropertyChanged(and others just don't need it). One example is DependencyObject. Can't inherit from BaseNotifyPropertyChanged class and DependencyObject at the same time.
In all the books and courses I take, people just keep duplicating the INotifyPropertyChanged implementation in all the base classes: BaseViewModel, BaseModel, BaseDataModel, BaseSynchronizableDataModel, just to name a few.
So I tried to do this:
interface IImplementNotifyPropertyChanged : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In order to then be able to do this:
class BaseViewModel : IImplementNotifyPropertyChanged {
}
And not actually have to implement INotifyPropertyChanged
members in the BaseViewModel
, because the default implementation is already in the IImplementNotifyPropertyChanged.
And then do the same in all other classes: I'd just add IImplementNotifyPropertyChanged
and that would be the end of INotifyPropertyChanged
implementation in all the classes that actually need it, without duplicating code and polluting the solution by deriving all my classes from BaseNotifyPropertyChanged class.
But I get these errors when I try to do this:
How to fix this error?
Please, help me to implement INotifyPropertyChanged
without duplicating the implementation code. Maybe there's some magical way with attributes or something? Like:
[Implements:INotifyPropertyChanged, ImplementNotifyPropertyChanged.cs]
class BaseViewModel {
}
Where Implements:INotifyPropertyChanged
would be the indicator of what interface this class implements and the ImplementNotifyPropertyChanged.cs
would be the name of the file where it can find members with which to implement it.