54

Say I have a class named Frog, it looks like:

public class Frog
{
     public int Location { get; set; }
     public int JumpCount { get; set; }


     public void OnJump()
     {
         JumpCount++;
     }

}

I need help with 2 things:

  1. I want to create an event named Jump in the class definition.
  2. I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.
TylerH
  • 20,799
  • 66
  • 75
  • 101
public static
  • 12,702
  • 26
  • 66
  • 86

2 Answers2

83
public event EventHandler Jump;
public void OnJump()
{
    EventHandler handler = Jump;
    if (null != handler) handler(this, EventArgs.Empty);
}

then

Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);

private void yourMethod(object s, EventArgs e)
{
     Console.WriteLine("Frog has Jumped!");
}
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • 1
    thanks, although I don't see the need for this line "EventHandler handler = Jump;" – public static Sep 17 '08 at 16:50
  • 14
    this is to avoid dead handlers.. in c# between the time you check if a handler is null and the actual time to invoke the handler the method could have been removed. So you set up a reference to where the handler is currently pointing then check for null on that reference and invoke. – Quintin Robinson Sep 17 '08 at 16:53
  • 4
    @publicstatic Regarding EventHandler handler = Jump; This can now (2015) be shortened to Jump?.Invoke(this, EventArgs.Empty); See: https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0 – erict Mar 25 '20 at 20:09
8

Here is a sample of how to use a normal EventHandler, or a custom delegate. Note that ?. is used instead of . to insure that if the event is null, it will fail cleanly (return null)

public delegate void MyAwesomeEventHandler(int rawr);
public event MyAwesomeEventHandler AwesomeJump;

public event EventHandler Jump;

public void OnJump()
{
    AwesomeJump?.Invoke(42);
    Jump?.Invoke(this, EventArgs.Empty);
}

Note that the event itself is only null if there are no subscribers, and that once invoked, the event is thread safe. So you can also assign a default empty handler to insure the event is not null. Note that this is technically vulnerable to someone else wiping out all of the events (using GetInvocationList), so use with caution.

public event EventHandler Jump = delegate { };

public void OnJump()
{
    Jump(this, EventArgs.Empty);
}
Tezra
  • 8,463
  • 3
  • 31
  • 68