views:

991

answers:

5

What is considered better style for an event definition:

public event Action<object, double> OnNumberChanged;

or

public delegate void DNumberChanged(object sender, double number);
public event DNumberChanged OnNumberChanged;

The first takes less typing, but the delegate one gives names to the parameters. As I type this, I think number 2 is the winner, but I could be wrong.

Edit: A different (third) approach is the winner. Read below.

+4  A: 

Don't create a new type if you don't have to. I think this is better:

public event Action<object, double> OnNumberChanged;

The reason that the Action and Func delegate families exist is to serve this very purpose and reduce the need for new delegate type creation by developers.

Andrew Hare
Agree with this one, one less line of code to maintain.
TreeUK
A: 

I think option 1 is better if I were to choose, but IIRC, the official guidelines for events state that your second parameter has to be a class with the name XxxEventArgs, and should have EventArgs up in its inheritance chain.

Dmitri Nesteruk
Yes you are right. They also advise that you do not start the event with the name "On", but you reserve this for the protected method that is used to raise your event.
Rob Levine
+14  A: 

Neither 1 or 2. A third option is the winner

public event EventHandler<NumberChangedEventArgs> NumberChanged;

You're breaking a number of style guidelines for developing in C#, such as using a type for event args that doesn't extend EventArgs.

Yes, you can do it this way, as the compiler doesn't care. However, people reading your code will do a WTF.

Will
+1 for style guidelines reference. I just would like to add that custom EventArgs might not be needed for property change notification event, because the change should have been reflected through the sender's property already.
tia
+1  A: 

As with all questions about coding style. Pick the one you prefer, or that your team prefers, and keep it consistent throughout the project. As long as everyone who needs to can read it efficiently you will be fine.

Matthew Vines
+1  A: 

Typically I stick to using an EventArgs derived class as the argument. It makes the code much more consistent.

I have a class:

public class ApplyClickedEventArgs : EventArgs  
{  
   ...
}

and a handler:

void cpy_ApplyClicked(object sender, ApplyClickedEventArgs e)  
{  
   ...  
}

The declaration is:

public event EventHandler<ApplyClickedEventArgs> ApplyClicked;
Brad Bruce