2 issues in our previous example ( See Implementing the Observer Pattern via Delegates post )
1. I can invoke the TrainSignal delegate directly
This means the TrainSignal object will tell subscribers that a train is coming when it’s not
Cars will stop but no train will come
Waste of everyone’s time
2. Inadvertently or on purpose unsubscribe observers without their knowledge
This means a train could be coming but the cars would not stop
Possibility of an accident -> problem




As we can see from the output, the cars stop but no train comes and then later, the train comes but the cars do not stop.
A note on the statement:
if (TrainIsComing != null)
TrainIsComing();
We’re checking if the invocation list of the delegate contains anything -> any methods to call. If there are no methods in the invocation list, it means there are no subscribers, hence nobody to notify, hence nothing to do.
In addition, TrainIsComing(); is syntactic sugar for TrainIsComing.Invoke(). If TrainIsComing is null, we will get a null reference exception.
We can resolve these 2 problems via EVENTS
Leave a comment