Override vs Events

  • Thread starter Thread starter Daisy
  • Start date Start date
D

Daisy

Any reason why I should use one of these over the other?

Overriding:

protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
// etc.
}


Events:

this.MouseDown += new MouseEventHandler(thisMouseDown);
public void thisMouseDown(object sender, MouseEventArgs e)
{
// etc.
}
 
Yes, there is a difference.

In the first one, you are overriding the method that causes the event. Thus,
no other methods that are registered as handling this event have fired (many
objects can register to execute methods from the same event). So this method
executes before the event fires, and if you cann the base class's
implementation, that will cause the event to fire, and for the registered
methods to fire.

In the second one, you are simply one of the objects who have registered to
receive the event once it fires, and to execute a particular method.
 
Marina said:
Yes, there is a difference.

In the first one, you are overriding the method that causes the event. Thus,
no other methods that are registered as handling this event have fired (many
objects can register to execute methods from the same event). So this method
executes before the event fires, and if you cann the base class's
implementation, that will cause the event to fire, and for the registered
methods to fire.

In the second one, you are simply one of the objects who have registered to
receive the event once it fires, and to execute a particular method.

I understand the differences, but it appears I can make both do what the
other does. I was wondering if there are any advantages or considerations
for doing it one way over the other. Eg. Any difference in registering for
the MouseDown event and overriding it and calling the base method?
 
Yes, in some cases you have to override. Especially when you want to
suppress the action that Windows or C# will take when that event is fired.
Or if you want to suppress it and replace it with another action. You can't
do that with an event.
 
Yes, basically what Allen said.

If you are interested in only doing something in response to an event, then
just register for the event.

If you need to change what happens when the event is raised: such as cancel
it, or perform some action right before or right after the event (and all
the methods registered for it)fires, then override the method.
 
Back
Top