Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override virtual method or create event handler? [closed]

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?

like image 490
Ryan Peschel Avatar asked Oct 17 '11 18:10

Ryan Peschel


2 Answers

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 :)

like image 90
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet


The decision of whether to override the method or use the event handler often times comes down to how much control you need to have over what happens during the execution of that method. Overriding the method gives you full control of the method, whereas the event handler only runs after the method has executed.

If you need a high level of control over what happens during that method, I would advise overriding the method. If you simply need to run some code after execution of the method, I would use the 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
}
like image 21
James Johnson Avatar answered Oct 05 '22 23:10

James Johnson