Search code examples
c#eventsderived-class

C# - Invoke Event Outside Of Declaring Class


I have an event in class Alice that I want to raise inside of a derived class Bob:

public class Alice
{
    public event Action<object> ValueChanged;
}

public class Bob : Alice
{
    public void method1(Alice bigAlice)
    {
        // raise ValueChanged event
        // or
        // raise ValueChanged event on bigAlice
    }
}

Compiler error says I can use only += and -= if I'm not in the declaring class of the event. How can I fire that event nevertheless from code of Bob ?


Solution

  • You could expose a protected method to invoke it:

    public class Alice {
      public event Action<object> ValueChanged;
    
      protected void RaiseValueChanged(object o) {
        if (ValueChanged != null) {
          ValueChanged(o);
        }
      }
    }