Signature .NET Events

Possible duplicate:
Why do events in C # accept (sender, EventArgs)?

I just ran the VS2012 code analysis tool in 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 "MyWebClient.PerMbHandler" as EventArgs or an instance of a type that extends EventArgs, named "e".

MSDN explains :

Event handler methods accept two parameters. The first type is of type System.Object and is called 'sender'. This is the object that raised the event. The second parameter is of type System.EventArgs and is called 'e'. This is event related data. For example, if an event occurs when a file is opened, these events usually contain the file name.

MSDN claims that this is an agreement and not the reason it exists.

What could go wrong using a long parameter rather than a subclass of EventArgs? Is this a matter of agreement and programmer, or is there some subtle technical reason for the pattern to be respected? I speak subtly because the code is working fine.

+4
source share
2 answers

What could go wrong if you use a long parameter and not a subclass of EventArgs?

Args Event
This is not in itself, but it is not extensible. For argumentation, perhaps after 6 months you need to go through two long ones or add a line or add an entire list of information. With EventArgs in the signature, you can pass any derived type and not violate existing consumers; with a specific type of value, you are very limited.

EventArgs also allows you to communicate with the class that raised the event, for example. CancelEventArgs .

Sender
Honestly, I rarely use a sender for anything. It can also be somewhat controversial. For example, a user event in a control triggered by input into a text field ... who is the sender? a text box (perhaps more useful) or a control declaring a custom event?

However, this is a familiar convention, and with a well-documented interface it can be useful.

+5
source

Nothing can go wrong; the signatures of the event and event handler are strongly typed. All this message warns you about speed, it gives another programmer who uses your event, puzzled by why the event has such an unusual signature. High-speed strokes give rise to errors that the producer programmer insists that he needs to get a sender, for example.

Keep in mind what FxCop does (aka Code Analysis). It does not check for errors that the job of the compiler. He should tell you about things you might not have thought of. Because of this, it can be a little annoying, especially when noodles about CAS or flags are notorious for the CA2000 inappropriately. But this is certainly a good warning, you did not think about it.

+2
source

Source: https://habr.com/ru/post/1442387/


All Articles