In a C# application, I've got a behaviour that I would like to be available in different classes that not necessarily share the same ancestor. What better opportunity to 'favour composition over inheritance?"
In this case not only composition is a better way, but can also be the only way.
Unfortunately, the code is the following. I left only the relevant part, obviously it would make little sense to delegate only this, but this is the problematic part.
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Turns out that since PropertyChanged is an event, it can only be raised inside the declaring class.
I evaluated all the proposed alternatives to this, found in this S&O question: Alternatives and all of them seems a bit of a hack. That is, events are not meant to be delegated. Fundamentally, I would like that someone proof me to be wrong on this point.
Unfortunately this seems to be another case of the pattern: you use inheritance? no no no, there is a better approach. And when you try to implement it you suddenly bump into problems that require various levels of hacking the language or bringing complexity of the solution to an whole other level.
At the end of the day inheritance or composition is not a marriage, so I don't want to stay with either of them for life; I considered myself to be married with the non-duplication, or DRY principle. So I wanted to find a good way of not repeating the code. Here I simply cannot find a reasonably-simple solution and hope that someone else that has already bumped into this problem proposed some perhaps 'third way' solution.
Fody.PropertyChanged
on all my classes that require anINotifyPropertyChanged
implementation. Problem solved, no inheritance required.