You need three things (which are marked with comments in the code):
- Declare an event in class B
- Raise an event in class B when something happened (in your case, the Button_Click event handler). Keep in mind that you need to check for subscribers. Otherwise, you will get a NullReferenceException when creating the event.
- Subscribe to an event of class B. You need to have an instance of class B that you even want to subscribe to (other option is static events, but these events will be raised by all instances of class B).
code:
class A { B b; public A(B b) { this.b = b; // subscribe to event b.SomethingHappened += MyMethod; } private void MyMethod() { } } class B { // declare event public event Action SomethingHappened; private void Button_Click(object o, EventArgs s) { // raise event if (SomethingHappened != null) SomethingHappened(); SomeMethod(); } public void SomeMethod() { } }
source share