As far as I can see, there are two main advantages:
- People writing code consuming an event will recognize the pattern and immediately learn how to use the event.
- The event signature is created in such a way that it is resistant to change.
The first point should be pretty obvious, without a lot of development.
As for the second point, there are two reasons for this (in my opinion). First, since the sender is an object , an event signature can be reused by several types. Secondly, since the second parameter is an EventArgs decendant, when you enter your own EventArgs class, this class can be extended later without changing the event signature.
Update
Answer to the questions:
I'm not sure what you mean by "the possibility of extending EventArgs without changing the signature of the event" ?!
Take an example, take the following class:
public class SomeClass { public event EventHandler<FileEventArgs> SomethingHappened; } public class FileEventArgs : EventArgs { public FileEventArgs(string filename) { Filename = filename; } public string Filename { get; private set; } }
Then we have a consumer that listens to the SomethingHappened event:
static void SomethingHappenedHandler(object sender, FileEventArgs e) {
Now let's say that we want to expand the information that we transmit in the case of information about what happened to the file:
public enum WhatHappened { Copy, Rename, Delete } public class FileEventArgs : EventArgs { public FileEventArgs(string filename, WhatHappened whatHappened) { Filename = filename; WhatHappened = whatHappened; } public string Filename { get; private set; } public WhatHappened WhatHappened { get; private set; } }
Now, if we decide to send the file name as a parameter in the event itself, we will need to change the signature of the event by adding another parameter, effectively breaking all the code that listens for the event. But since in the code above we simply added another property to the FileEventArgs class, the signature remains unchanged, and no listener should be updated (unless they want to use the newly added property, that is).
I write, assuming that if an event occurs inside a static method, then the parameter "source of the object" does not matter to use ?!
Yes, that's right. I usually pass null as the sender argument from static events (which, frankly, is very rare).