none
code onEvent method using extension method RRS feed

  • Question

  • I have an event defined in an interface.  Would like to code the OnEvent method within an extension method of that interface. But the C# compiler says "the event can only appear on the left hand side of +=".  Which kind of stinks. I do not want to have repeat the OnEvent method in each of the classes that implement the interface.  

    Do I have any other options?   I am thinking to push the event down to a base class. But the classes really do not have commonality that the base class would imply.

    thanks,

      public interface ISectionHeader
      {
        IList<IScreenItem> Items { get; }
    
        event Action<ISectionHeader, IScreenItem> SectionHeaderChanged;
      }
    
      public static class ISectionHeaderExt
      {
        public static void OnSectionHeaderChanged(this ISectionHeader header, IScreenItem item)
        {
    
          if (header.SectionHeaderChanged != null)
          {
            header.SectionHeaderChanged(header, item);
          }
        }
      }
    
    
      public class ScreenSection : ISectionHeader
      {
    
        public event Action<ISectionHeader, IScreenItem> SectionHeaderChanged;
    
        public void OnSignalSectionHeaderChanged(IScreenItem item)
        {
          if ( this.SectionHeaderChanged != null)
          {
            this.SectionHeaderChanged(this, item);
          }
        }
    }
    
    

    Saturday, October 1, 2016 7:55 PM

Answers

  • Create an abstract base class. Otherwise your derived classes could have a different behavoiur when raising the event.

    Using the same interface on different classes makes them already have something in common.

    btw, use this idiom, otherwise the handler could be set null between the if conditional test and the call:

    event Action<ISectionHeader, IScreenItem> handler = this.SectionHeaderChanged;
    if (handler != null)
    {
      handler(header, item);
    }


    Saturday, October 1, 2016 9:16 PM