Lets say I create an abstract class that manages some network functionality for
ID: 645830 • Letter: L
Question
Lets say I create an abstract class that manages some network functionality for me.
I want to be able to be notified when something changes. For example: OnConnect or OnDisconnect.
Should I create events for those kinds of functions or implement them as abstract methods?
public event OnConnectDelegate OnConnected;
or:
protected abstract OnConnected(SomeClientObject connectedClient);
I prototyped both solutions and both work as expected. But how do I know in general if I should expose functionality as an event or as an abstract method? Are there any situations where I should clearly prefer one over the other? Events support multiple receivers but one also has to remove them when the receiver doesn't need to receive them anymore.
Explanation / Answer
Of the now partially outdated but still useful article from MSDN: "When to Use Delegates Instead of Interfaces (C# Programming Guide)", a few of the rules-of-thumb stand out:
Use a delegate in the following circumstances:
(3) The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
My explanation:
The callee (event receiver) can easily get hold of the caller (sender) because by best practice the caller will pass itself as the first argument (aptly named sender) to the callee.
However, trying to navigate in the reverse direction is non-trivial. A delegate could be anything
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.