When should one do the following?
class Foo : Control
{
protected override void OnClick(EventArgs e)
{
// new code here
}
}
Overriding rather than attaching a delegate will result in more efficient code, so it is generally recommended that you always do this where possible. For more information see this MSDN article. Here is a pertinent quote:
The protected OnEventName method also allows derived classes to override the event without attaching a delegate to it. A derived class must always call the OnEventName method of the base class to ensure that registered delegates receive the event.
An inherited class should never subscribe to it's own events, or it's base class' events.
Now, if a class has an instance of another, different, class in it, then it can consume that class' events, and determine if it should raise it's own event or not.
For example, I rolled out a MRU List class recently. In it, there was a number of ToolStripMenuItem controls, whose click event I consumed. After that click event was consumed, I then raised my class's event. (see that source code here)
Be aware that (at least in .NET 2.0) I have found a few places in the framework (specifically in the DataTable class) where the OnFoo method is only called when the corresponding Foo event has been handled! This contravenes the framework design guidelines but we're stuck with it.
I've gotten around it by handling the event with a dummy handler somewhere in the class, eg:
public class MyDataTable : DataTable
{
public override void EndInit()
{
base.EndInit();
this.TableNewRow += delegate(object sender, DataTableNewRowEventArgs e) { };
}
protected override void OnTableNewRow(DataTableNewRowEventArgs e)
{
base.OnTableNewRow(e);
// your code here
}
}
If you override like Kent Boogaart comments you'll need to be carefull to call back base.OnClick to allow event suscriptions to be called
Subscribing to the event is intended for a control to monitor events on a different control. For monitoring your own event OnClick is fine. Note, however, that Control.OnClick handles firing those subscribed events, so be sure to call it in your override.
It is worth noting that there are some corner cases where it only works with handlers and not with OnEvent overrides. One such example-
Why style is not applied when I'm removing StartupUri in WPF?