Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you override OnEvent as opposed to subscribing to the event when inheritting

When should one do the following?

class Foo : Control
{
    protected override void OnClick(EventArgs e)
    {
        // new code here
    }
}

As opposed to this?

class Foo : Control
{
    public Foo()
    {
        this.Click += new EventHandler(Clicked);
    }

    private void Clicked(object sender, EventArgs e)
    {
        // code
    }
}
like image 792
MagicKat Avatar asked Oct 01 '08 19:10

MagicKat


4 Answers

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.

like image 148
James Curran Avatar answered Nov 06 '22 16:11

James Curran


The event is for external subscribers. When you are deriving some control, always override the OnEvent method instead of subscribing to the event. This way, you can be sure when your code is called, because the actual event is fired when you call base.OnEvent(), and you can call this before your code, after your code, in the middle of your code or not at all. You can then also react on return values from the event (i.e. changed properties in the EventArgs object).

like image 33
OregonGhost Avatar answered Nov 06 '22 16:11

OregonGhost


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.

like image 10
Kent Boogaart Avatar answered Nov 06 '22 16:11

Kent Boogaart


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
    }
}
like image 4
Matt Hamilton Avatar answered Nov 06 '22 16:11

Matt Hamilton