Considering the code below:
public class TableMain { public virtual event Action UpdateFilter; .... } public class TableSub : TableMain { public override event Action UpdateFilter; public void UpdateQuery() { ..... if (UpdateFilter!=null) { UpdateFilter(); // Invocation of polymorphic field-like event??? } } }
In this code ReSharper shows the alert "invocation of polymorphic field-like event".
My question is: What does it actually mean? And is it an alert for a bad programming practice? Also, is it a bad practice to call an event polymorphically? (Knowing that an event can only be raised from the class which has declared it.)
Well, you've actually got two field-like events here. Your override will be overriding the add/remove part, but you'll have two fields - one in TableMain
and one in TableSub
. Only the one in TableSub
will ever be non-null, unless the value is set explicitly in TableMain
... so if TableMain
ever tries to raise the event itself, it won't call the same set of handlers as in TableSub
. Basically, it's going to behave strangely.
The right approach is to provide a protected method in TableMain
to allow the event to be raised by subclasses:
protected void OnUpdateFilter() { Action handler = UpdateFilter; if (handler != null) { handler(); } }
Then make the event non-virtual, and remove the override in TableSub
.
Note that your event signature doesn't match the normal convention for events - any reason for not using EventHandler
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With