#381 – Implementing an Event that Returns Some Data
August 3, 2011 Leave a comment
When you implement an event, you can define your own delegate type, or you can use the existing EventHandler or EventHandler<TEventArgs> types.
If you want your event to return some data, you should:
- Create a new class that inherits from EventArgs for the event’s data
- Use the EventHandler<TEventArgs> delegate type
Start by defining new EventArgs-based class that will store the event’s data.
public class BarkedEventArgs : EventArgs { public string BarkSound { get; protected set; } public BarkedEventArgs(string barkSound) { BarkSound = barkSound; } }
Then, in your class, declare the event and a helper method to raise the event.
// Declare the event public event EventHandler<BarkedEventArgs> Barked; // Helper method that raises the event protected virtual void OnBarked(string sound) { if (Barked != null) Barked(this, new BarkedEventArgs(sound)); }
Finally, raise the event whenever a Dog barks.
public void Bark(string barkSound) { Console.WriteLine(barkSound); OnBarked(barkSound); }