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:
- I want to create an event named Jump in the class definition.
- I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.
then
@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: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)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.