Can anyone provide me with general guidelines as to when I should use overridable methods such as "OnMyEvent", and when I should use events such as "MyEvent" in C#?
Are there any general design principles that can define what to use?
The two features are vaguely similar (both are designed to do some form of dynamic dispatch), but are not directly comparable.
Events are to notify other objects that an object has come to some sort of state transition. It is a language feature that embodies the Observer Design Pattern. This can be useful in a lot of cases, but is not always useful or desirable. It is a tool to get specific jobs done.
Virtual functions are used to create Object Oriented Polymorphism. They are a basic building block of nearly every Design Pattern, and a lot of object oriented design.
To try to compare them, I'll assume you're trying to implement some form of observer pattern with either feature. With that restriction in place, there is still no simple rule you can fall back on to decide which you should use. Instead, you'll have to ask yourself questions like:
If it is triggered internally, you could use an event or a virtual method. If it is triggered externally, you must use a virtual method.
If the class that owns the state should handle the transition, then it should be a virtual method. If a separate class should react to the transition, it should be an event.
If you need one, then either using a virtual method or an event could be acceptable. If you need many, then it will be much easier to use an event.
If you need your handlers to change, you must use events. If you only have a single handler that is known at compile time, you could use a virtual method.
If it belongs in a derived class, you need a virtual method. If it belongs elsewhere, then you need an event.
As you can see, the answers will greatly depend on your specific problem domain and object architecture. Good design isn't something that magically falls into your lap via some check list. You have to think about it, a lot :)
Edit:
It may not be directly applicable to C# events, but it may be useful to take example from existing work. Here is a brief article I just found (while answering a different question) on design alternatives in Java for eventing patterns: http://csis.pace.edu/~bergin/patterns/event.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With