Search code examples
c#eventscoding-stylevirtual

Override virtual method or create event handler?


Was just messing around looking at the XNA documentation for the Game class and noticed there is a Deactivated event and an OnDeactived virtual method one can override.

Both creating an event handler for the Deactivated event and overriding the OnDeactived virtual method allows the client to handle the game losing focus.

I was wondering which approach should be used generally to handle the game losing focus. Creating an event handler or overriding the virtual method? Are there any differences between each approach?


Solution

  • There are two obvious differences:

    • You can only override OnDeactivated within a class derived from the one declaring it - mere "other" code can only use the event
    • Within OnDeactived, it's up to you to decide whether or not to call base.OnDeactivated - you could effectively suppress the event, or change the parameters; invoke it before or after your own code, etc.

    If you're already deriving from the class, either way would work - personally I'd probably use the event more often than not, unless I wanted to take any other sort of action that could only be performed by overriding. Aside from anything else, that makes the code more portable if you want to move it anywhere else. Then again, I'm generally not a fan of inheritance anyway, so I'm biased :)