I understand how to use Events according to Net Framework guidelines, but what are the benefits of using this pattern?
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx :
The .NET Framework guidelines indicate that the delegate type used
for an event should take two parameters, an “object source” parameter
indicating the source of the event, and an “e” parameter that
encapsulates any additional information about the event. The type of
the “e” parameter should derive from the EventArgs class. For events
that do not use any additional information, the .NET Framework has
already defined an appropriate delegate type: EventHandler.
a) I see some benefits in using “object source” value as a first parameter since there are situations where multiple objects can have their events set to the same method. Thus, if for example we have 10 objects and if all 10 objects set their events to event handler M, then inside M we can use “object sender” parameter value to identify the initiator of the event call.
- But as far as I can tell, ”object source” parameter is only useful if event was raised inside an instance method. Thus, if event was raised inside static method, then “object source” parameter is of no use?!
b) Are there other benefits of using events with accordance to Net Framework guidelines?
c) Whatever the benefits may be, why would they out-weight the trouble of having to
- write an additional code to put the desired arguments into an object derived from EventArgs
- write an additional code inside event handlers to extract information from object derived from EventArgs ?
thank you
As far as I see it there are two major benefits:
The first point should be pretty obvious, not needing a lot of elaboration.
As for the second point, there are two reasons for this (in my opinion). First, since sender is
object, the event signature can be reused by several types. Second, since the second parameter is anEventArgsdecendant, when you introduce your ownEventArgsclass this class can be extended later without altering the signature of the event.Update
Response to questions:
Let’s take an example, take the following class:
Then we have a consumer that listens to the
SomethingHappenedevent:Now, lets say that we want to extend the information that we transfer in the event with information about what happened to the file:
Now, if we had chosen to send the filename as a parameter in the event itself, we would need to alter the event signature by adding another parameter, effectively breaking all code that listens to the event. But since we in the code above have simply just added another property to the
FileEventArgsclass, the signature remains unchanged, and no listeners need to be updated (unless they want to use the newly added property, that is).Yes, that is correct. I typically pass
nullas the sender argument fromstaticevents (which, honestly, is very rare).