This is a mirror of official site: http://jasper-net.blogspot.com/

C#/.NET Little Wonders: The EventHandler and EventHandler delegates

| Sunday, November 20, 2011
Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

In the last two weeks, we examined the Action family of delegates (and delegates in general), and the Func family of delegates and how they can be used to support generic, reusable algorithms and classes.

So this week, we are going to look at a handy pair of delegates that can be used to eliminate the need for defining custom delegates when creating events: the EventHandler and EventHandler<TEventArgs> delegates.
Events and delegates

Before we begin, let’s quickly consider events in .NET.  According to the MSDN:

    An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.

So, basically, you can create an event in a type so that users of that type can subscribe to notifications of things of interest.  How is this different than some of the delegate programming that we talked about in the last two weeks?  Well, you can think of an event as a special access modifier on a delegate.  Some differences between the two are:

    Events are a special access case of delegates
        They behave much like delegates instances inside the type they are declared in, but outside of that type they can only be (un)subscribed to.
    Events can specify add/remove behavior explicitly
        If you want to do additional work when someone subscribes or unsubscribes to an event, you can specify the add and remove actions explicitly.
    Events have access modifiers, but these only specify the access level of those who can (un)subscribe
        A public event, for example, means anyone can (un)subscribe, but it does not mean that anyone can raise (invoke) the event directly.
    Events can only be raised by the type that contains them
        In contrast, if a delegate is visible, it can be invoked outside of the object (not even in a sub-class!).
    Events tend to be for notifications only, and should be treated as optional
        Semantically speaking, events typically don’t perform work on the the class directly, but tend to just notify subscribers when something of note occurs.

My basic rule-of-thumb is that if you are just wanting to notify any listeners (who may or may not care) that something has happened, use an event.  However, if you want the caller to provide some function to perform to direct the class about how it should perform work, make it a delegate.


Read more: James Michael Hare
QR: c.net-little-wonders-the-eventhandler-and-eventhandlerteventargs-delegates.aspx

Posted via email from Jasper-net

0 comments: