Reputation: 27727
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.
Upvotes: 9
Views: 4817
Reputation:
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.
Upvotes: 16
Reputation: 7827
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;
Upvotes: 2
Reputation: 27581
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.
Upvotes: 1
Reputation: 23798
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.
Upvotes: 0
Reputation: 351566
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.
Upvotes: 11