Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

Useful additions in .NET 2.0 - Part 3: EventHandler<TEventArgs>

If your .NET class needs to generate events, at a minimum, you typically do the following:

1) Create a new class which derived from EventArgs – the instance of this class would be used to communicate certain information to the event handler about the event itself. For example, CacheExpiryEventArgs. 

2) A new delegate type whose instance points to a method, the signature of which looks something like:

      public delegate void CacheExpiryEventHandler(object sender, CacheExpiryEventArgs e);

 3) You declare an event which is associated with the delegate you created in (2). For example,

      public event CacheExpiryEventHandler CacheExpired

Now, for every event in your application, you invariably create as many delegate types. If you notice, each of those delegates differs only by the second argument of the event handler – the class representing the event arguments. Now, wouldn’t it be great if you had a generic delegate parameterized by the respective EventArgs argument. With generics in .NET 2.0, this is exactly what you get, in the form of EventHandler<TEventArgs>. With this in place, our example now would look like:

     public event EventHandler<CacheExpiryEventArgs> CacheExpired;

This is definitely convenient, as it would reduce the number of delegates that are created in any application. Generics is a great addition in .NET 2.0, which not only gives you performance and strong-typing, but also certain productivity benefits like in this case, and for that matter Nullable<T>, List<T> and may such instances.

Posted: Jan 02 2006, 12:28 AM by Manoj G | with 1 comment(s) |
Filed under:

Comments

Dmytro said:

Thanks a lot, really handy technique.
# March 1, 2006 4:25 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)