Guest User

Guest User

  • Tech Writer
  • 48
  • 11.1k

How to add an event to a static method in a class?

Aug 2 2019 2:41 PM
I am looking to add an event to a class, and I am using the following answer from stackexchange as a base:
https://stackoverflow.com/questions/85137/how-to-add-an-event-to-a-class
 
The answer example registers the event every time the frog object jumps.
  1. public event EventHandler Jump;
  2. public void OnJump()
  3. {
  4.     EventHandler handler = Jump;
  5.     if (null != handler)
  6.         handler(this, EventArgs.Empty);
  7. }
  8. Frog frog = new Frog();
  9. frog.Jump += new EventHandler(yourMethod);
  10. private void yourMethod(object s, EventArgs e)
  11. {
  12.     Console.WriteLine("Frog has Jumped!");
  13. }
Now this is fine for non-static methods, but the problem is I have a static method in my class, so the "this" keyword won't work. Here is my version of the code:
 
  1. // In my class file.   
  2. public event EventHandler Triggered;  
  3. public static void Trigger()  
  4. {  
  5.   EventHandler h = Triggered;  
  6.   if (h != null)  
  7.     h(this, EventArgs.Empty);  
  8. }  
  9.    
  10. // In my main file.
  11. MyClass myObj = new MyClass();  
  12. myObj.Trigger += new EventHandler(TakeAction);  
  13.    
  14. private void TakeAction(object o, EventArgs e)  
  15. {  
  16.   Console.WriteLine("We made it.");  
  17. }  
"this" in line 7 cannot be used due to the static nature of the funciton. How can I modify this code so that it allows this event to be properly registered.

Answers (1)