Override virtual method or create event handler?

Just messing around with the XNA documentation for the game class, and noticed that there was a Deactivated event and a virtual OnDeactived method that could be overridden.

Both creators of the event handler for the Deactivated event and overrides of the OnDeactived virtual method allow the client to process the game, losing focus.

I was wondering which approach should be used in general to deal with the loss of focus. Creating an event handler or overriding a virtual method? Are there differences between each approach?

+8
c # coding-style events virtual
source share
2 answers

There are two obvious differences:

  • You can only override OnDeactivated in a class that is derived from the declaration declaring it - a simple "different" code can use the event
  • Inside OnDeactived you decide whether to call base.OnDeactivated - you could effectively suppress the event or change the parameters; call it before or after your own code, etc.

If you are already leaving the class, any of them will work - personally, I probably would have used this event more often than if I did not want to take any other actions that could be performed only by redefinition. Among other things, this makes the code more portable if you want to move it to another location. Again, I'm not a fan of inheritance at all, so I'm biased :)

+7
source share

The decision about whether to override a method or use an event handler often comes down to how much control you need to have over what happens during the execution of this method. Overriding a method gives you complete control over a method, while an event handler is only triggered when the method is executed.

If you need a high level of control over what happens during this method, I would suggest overriding the method. If you just need to run some code after the method is executed, I would use an event handler.

 protected override void OnDeactivated(EventArgs e) { //run some code before execution (anything that could effect execution) //call the base method and fire the event base.OnDeactivated(e); //run some code after execution } 
+1
source share

All Articles