tags:

views:

138

answers:

4

I understand the benefits of events using delegate types with signature delegate void delegate_name(object sender, EventArgs e)

a) But besides the fact that it may save us some typing, are there any other reasons why we should use already defined delegate types EventHandler/EventHandler<T> instead of declaring our own delegate types with signature delegate void delegate_name(object sender, EventArgs e)?

b) Two other reason I can think of for using the predefined delegate types EventArgs/EventArgs<T> are:

  • people consuming particular event ( say event EventHandler my_event ) will immediately know how to use that event?

  • perhaps some popular third party methods accept as parameters EventHandler/ EventHandler<T> delegate types, and thus if there’s any chance that our code may use those third party methods, we should use predefined delegates EventHandler/Eventhandler<T>?

thank you

+8  A: 

To me, the question is a little strange. What would be the benefit of doing this otherwise (defining delegate types that exactly match EventHandler<TEventArgs> for some TEventArgs)?

That said, there is at least one benefit I can think of to doing it the "normal" way: certain APIs already expect to deal with EventHandler<TEventArgs> delegates; for example, Rx Extensions includes a method that looks like this:

Observable.FromEvent<TEventArgs>(
    Action<EventHandler<TEventArgs>> addHandler,
    Action<EventHandler<TEventArgs>> removeHandler
);

If you defined your own delegate, using methods like this -- which expect EventHandler<TEventArgs> delegates -- would become more complicated than necessary for no added benefit (that I can see, anyway).

Dan Tao
thank you all for your help
flockofcode
+3  A: 

You've answered your own question:

  • Syntactical Sugar (less to write) to maintain the convention
  • Interoperability (using the EventHandler type let's you easily integrate events from other libraries

In short; there's no good reason not to use it unless you're forced to (which typically is the result of people not being aware of it, or not understanding it).

STW
+6  A: 

You forgot an important one:

  • the lunatic that will maintain your code some day will find out where you live and hurt you.
Hans Passant
+1 This is a legitimate concern, I think!
ewall
+2  A: 

From Pro C# 2008 and the .NET 3.5 Platform:

When the compiler processes the event keyword, you are automatically provided with registration and unregistration methods* as well as any necessary member variables** for your delegate types. ...To be sure, the event keyword is little more than syntactic sugar in that it simply saves you some typing time.

* This includes overloading the handy += and -= operators.

** ...which are already marked private so they can't end-run.

When you use the generic EventHandler delegate, you don't even have to write out your custom delegate type at all.

ewall