The overridden method is preferrable as it will be invoked polymorphically virtually by the CLR.
[Edit] Here is why I believe the overridden method is preferable:
Here is a simple example:
class Foo
{
public event EventHandler Changed = delegate { };
protected virtual void OnChanged()
{
this.Changed(this, EventArgs.Empty);
}
}
class Bar : Foo
{
public Bar()
{
this.Changed += new EventHandler(this.Bar_Changed);
}
void Bar_Changed(Object sender, EventArgs e) { }
}
class Baz : Foo
{
protected override void OnChanged()
{
base.OnChanged();
}
}
Now I believe the Baz
is the better implementation and here is why. Bar
must do the following IL instructions to wire up the event:
L_000a: ldftn instance void Bar::Bar_Changed(object, class [mscorlib]System.EventArgs)
L_0010: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int)
L_0015: call instance void Foo::add_Changed(class [mscorlib]System.EventHandler)
We must create a delegate to the handling method, an instance of the EventHandler
and then call the add_Changed
method on the event in the base class. While these are not performance killers none of the previous code is required for Baz
to work. Since any call to OnChanged
will be virtual the only performance penalty will be the CLR finding the right instance method to call in the inheritance chain.