Correct me if i’m wrong, but i believe most (if not all) classes in the CLR that raise events raise those events from protected methods, for example Form.OnMouseDown… so…
In a subclass, when would you want to override the “OnXyzMethod” instead of simple adding an event handler like Visual Studio does by default when you want to handle a controls event?
The only thing that occurs to me is that I might want to override the method to prevent the event from actually being raised… not that i can think of when that might apply…
The
OnEventmethod is provided in order to raise the event. This method is usually virtual so that you may change how and when the event is raised in a derived class. You should only override this method if you’re changing either of those things.If, for example, it wasn’t appropriate to raise the event in a subclass under certain conditions (e.g. an object that is a disabled state), you could override the default
OnEventbehaviour to prevent the event being raised.You should not override the
OnEventmethod to add behaviour in response to the event occuring; that’s the purpose of event handlers.