#379 – Using the EventHandler Delegate for Events that Return No Data
August 1, 2011 4 Comments
When you add an event to a class, you can use any delegate you like for the event’s type. For example, you could based the event on a delegate that accepts a single parameter of type string:
public delegate void StringHandlerDelegate(string s); public event StringHandlerDelegate Barked;
It’s recommended, however, that you use the one of the following two preexisting types as the delegate type:
- EventHandler – for event that return no data
- EventHandler<TEventArgs> – for event that returns some data
Below is an example of an event that returns no data. The Dog.Barked event is raised when a Dog object barks.
// Declare the event public event EventHandler Barked; // Helper method that raises the event protected virtual void OnBarked() { if (Barked != null) Barked(this, null); } // In Bark method, call helper to raise the event public void Bark() { Bark("Woof"); OnBarked(); }
I don’t fully understand why this EventHandler delegate types are recommended. Why we just can’t use delegates and benefit from their MultiCasting functionality, instead of declaring Events, which from my perspective are just plain wrappers for delegates…
Yes, you’re right. You could add a member whose type is a delegate to the class and use it directly from the client code, adding and removing handler methods. So far, this is what the client code can do from an event. But if you use a delegate, the client code can also do additional things–like examining the invocation list and even setting the delegate instance to null. If what you really want as the author of a class is for clients to be able to subscribe to your events, then an event limits the client to this behavior. This is an example of encapsulaton–where you expose only the desired functionality to the client code and no more.
See also https://csharp.2000things.com/2011/08/08/384-the-difference-between-delegates-and-events/
Makes sense now, thanks! 🙂