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:
Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method On EventName; for example, OnDataReceived .
Right-click the control for which you want to handle the notification event. On the shortcut menu, choose Add Event Handler to display the Event Handler Wizard. Select the event in the Message type box to add to the class selected in the Class list box.
Events in C# are simple things on the face of it. You create an event signature using a delegate type and mark it with the event keyword. External code can register to receive events. When specific things occur within your class, you can easily trigger the event, notifying all external listeners.
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!"); }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With