Reputation: 3217
Is it a bad practice to override an Event Handler, compared to calling a protected method from the Event Handler and overriding the protected method.
Are there any security concerns, or any side effects if you override an Event Handler.
namespace Testing
{
public class Owner
{
public event EventHandler<EventArgs> OnAction;
}
public class Foo
{
public Foo(Owner owner)
{
owner.OnAction += OnAction;
owner.OnAction += OnAction2;
}
protected virtual void OnAction(object sender, EventArgs eventArgs)
{
}
private void OnAction2(object sender, EventArgs eventArgs)
{
ProtectedMethod();
}
protected virtual void ProtectedMethod()
{
}
}
public class FooDerived: Foo
{
public FooDerived(Owner owner) : base(owner)
{
}
protected override void OnAction(object sender, EventArgs eventArgs)
{
// Do Something
base.OnAction(sender, eventArgs);
}
}
public class FooDrived2: Foo
{
public FooDrived2(Owner owner) : base(owner)
{
}
protected override void ProtectedMethod()
{
// Do something
base.ProtectedMethod();
}
}
}
Upvotes: 0
Views: 111
Reputation: 9399
I can only think of one case where overriding an event handler would be useful.
Say you have an event which gives you an event handler of a given type. If you wish to change the parameters passed to the methods that will be called by the handler, then you can override it. Otherwise overriding them is just a noop.
If the parameters will be the same anyway (or if their types are child types of the ones declared in the original handler) and you want the derived class to handle the event in a different way, then you should override its methods.
Upvotes: 1
Reputation: 37533
I wouldn't say it's bad practice to override the event handler's delegate method. It's a method like anything else. That being said, it's not something I would normally do. If I had a need for any kind of overriding, I would build (and implement) an interface with all of my method signatures. Then the overriding/shadowing/hiding/whatever would occur on accepted interface methods and the events would simply be add-on methods that would be responsible for calling the appropriate interface method.
Overriding the event handler directly wouldn't be any less readable (or maintainable IMO). Interfaces are just my habit to help with testing and scalability.
Upvotes: 2