Notify when an event is fired from another class

I have

class A { B b; //call this Method when b.Button_click or b.someMethod is launched private void MyMethod() { } ?? } Class B { //here ie a button is pressed and in Class A //i want to call also MyMethod() in Class A after the button is pressed private void Button_Click(object o, EventArgs s) { SomeMethod(); } public void SomeMethod() { } ?? } 

Class A has an instance of class B.

How can I do that?

+6
source share
3 answers

You need to declare a public event in class 'B' - and subscribe to it as follows:

Something like that:

 class B { //A public event for listeners to subscribe to public event EventHandler SomethingHappened; private void Button_Click(object o, EventArgs s) { //Fire the event - notifying all subscribers if(SomethingHappened != null) SomethingHappened(this, null); } .... class A { //Where B is used - subscribe to it public event public A() { B objectToSubscribeTo = new B(); objectToSubscribeTo.SomethingHappened += HandleSomethingHappening; } public void HandleSomethingHappening(object sender, EventArgs e) { //Do something here } .... 
+27
source

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() { } } 
+6
source
+1
source

All Articles