views:

432

answers:

3

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.
+5  A: 
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
thanks, although I don't see the need for this line "EventHandler handler = Jump;"
public static
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
A: 

I'm not too clear on your question. Do you want to know the syntax for events? Why not look at the tutorial in the official documentation?

Konrad Rudolph
A: 

@CQ: Why do you create a local copy pf Jump? Additionally, you can save the subsequent test by slightly changing the declaration of the event:

public event EventHandler Jump = delegate { };

public void OnJump()
{
    Jump(this, EventArgs.Empty);
}
Konrad Rudolph
Creating the local copy is a defensive technique that prevents an exceptin from ocurring if the handler is removed before it actually gets a chance to run.
Scott Dorman
Also, if you don't check for null, you will get a NullReferenceException if there are no event handlers attached to the event when calling Jump(this, EventArgs.Empty);
Abe Heidebrecht
Scott, you're assigning a reference here so this “defensive technique” is completely useless.
Konrad Rudolph
Abe, the check for `null` is redundant in my code because the object will *never* be null (notice the initialization!)
Konrad Rudolph
It's not useless. The defensive technique is for when the subscriber unsubscribes from the event between the null check and the actual function call. Your method creates a useless function for every instance of the class and calls the function (with necessary overhead) every time the event fires.
toast