Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invocation of a polymorphic field-like event

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.)

like image 723
Manish Basantani Avatar asked Oct 15 '10 06:10

Manish Basantani


1 Answers

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?

like image 86
Jon Skeet Avatar answered Sep 20 '22 04:09

Jon Skeet