Code Inspection: Invocation of polymorphic field-like event
Consider the following piece of code:
public class Base
{
public virtual event EventHandler MyEvent;
}
public class Derived : Base
{
public override event EventHandler MyEvent;
public void SomeMethod()
{
var args = ...;
MyEvent(this, args);
}
}
The above block of code uses an overriding event declaration to override the implementation of the add and remove methods on an event. The field itself will then exist in two separate instances - one in Base
and one in Derived
. As a consequence, when working with Derived
, you are likely to never instantiate the Base
's MyEvent
unless you explicitly set it to some value. And, as a result of that, the behavior in the case when the event is raised in the base class would differ from that in the derived class.
The simplest way to resolve the above situation is to get rid of the override and instead to create an event-firing method in the base class. For example:
public class Base
{
public event EventHandler MyEvent;
public void FireMyEvent(object sender, EventArgs args)
{
var e = MyEvent;
if (e != null)
e(sender, args);
}
}
public class Derived
{
public void SomeMethod()
{
var args = ...;
FireMyEvent(this, args);
}
}
Last modified: 21 March 2024