Possible Duplicate:
Why should events in C# take (sender, EventArgs)?
I just ran the VS2012 Code Analysis tool on a project and found that it complains about this snippet:
public delegate void PerMbHandler(long totalMb);
public event PerMbHandler NotifyMegabyteIncrement;
CA1009 Declare the second parameter of ‘MyWebClient.PerMbHandler’ as an EventArgs, or an instance of a type that extends EventArgs, named ‘e’.
Event handler methods take two parameters. The first is of type System.Object and is named ‘sender’. This is the object that raised the event. The second parameter is of type System.EventArgs and is named ‘e’. This is the data that is associated with the event. For example, if the event is raised whenever a file is opened, the event data typically contains the name of the file.
MSDN states simply what the convention is, not the reason it exists.
What can go wrong using a long parameter rather than a subclass of EventArgs? Is it a matter of convention and programmer expectations, or is there some subtle technical reason that the pattern must be followed? I say subtle, because the code seems to work fine.
Event Args
It’s not wrong per se but it’s not extensible. For sake of argument, perhaps in 6 months you need to pass two longs, or add a string, or add a whole list of information. With
EventArgsin the signature, you can pass any derived type and not break existing consumers; with a specific value type, you are very limited.EventArgs also allows you to communicate with the class that raised the event, e.g.
CancelEventArgs.Sender
Honestly, I rarely use sender for anything. It can also be somewhat ambiguous. For example, a custom event on a control triggered by input into a textbox…who is the sender? the textbox (probably more useful), or the control which declares the custom event?
Still, it is a familiar convention, and with a well-documented interface it can be useful.