.NET EventHandlers - Generic or no?
        Posted  
        
            by Chris Marasti-Georg
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Chris Marasti-Georg
        
        
        
        Published on 2008-09-24T19:50:41Z
        Indexed on 
            2010/04/12
            8:43 UTC
        
        
        Read the original article
        Hit count: 541
        
Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item.  I stick with the EventHandler/EventArgs practice, but what I like to do is have something like:
public delegate void EventHandler<T>(object src, EventArgs<T> args);
public class EventArgs<T>: EventArgs {
  private T item;
  public EventArgs(T item) {
    this.item = item;
  }
  public T Item {
    get { return item; }
  }
}
Later, I can have my
public event EventHandler<Foo> FooChanged;
public event EventHandler<Bar> BarChanged;
However, it seems that the standard for .NET is to create a new delegate and EventArgs subclass for each type of event.  Is there something wrong with my generic approach?
EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic
EventHandler<TEventArgs>, so you don't need to create the generic delegate, but you still need the generic EventArgs<T> class, because TEventArgs: EventArgs.
Another EDIT: One downside (to me) of the built-in solution is the extra verbosity:
public event EventHandler<EventArgs<Foo>> FooChanged;
vs.
public event EventHandler<Foo> FooChanged;
It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?
© Stack Overflow or respective owner