Most .NET stock events are have this signature:
delegate void SomethingSomething(SomethingEventArgs e); event SomethingSomething OnSomethingSomething;
and
class SomethingEventArgs { public string Name; public int Index; public double Groar; }
Why is that better (obviously is, otherwise anyone would choose to do) than:
delegate void SomethingSomething(string Name, int Index, double Groar); event SomethingSomething OnSomethingSomething;
since you don't have to pack your parameters to an object, and without initializers (.NET 2.0) it was kind of typing exercise.
One reason that comes to mind is that you can return your values simpler when having them packed in an object - ie. handler can modify a member of the object. However, with multicast events, that can't always be good anyway.
So, why?
The first parameter represents the object raising the event. The second, called the event argument, contains information specific to the event, if any. For most events, the event argument is of type EventArgs, which does not expose any properties.
EventArgs is a base class for conveying information for an event.
AssemblyLoadEventArgs class derives from EventArgs and is used to hold the data for assembly load events. To create a custom event data class, create a class that derives from the EventArgs class and provide the properties to store the necessary data. The name of your custom event data class should end with EventArgs .
EventArgs is the base class of all event arguments and doesn't say much about the event. Several events use a derived class to supply more data, eg. a KeyPress event uses the KeyEventArgs class which contains the actual key pressed in its KeyChar property.
Read about Open/Closed principle.
By using a class, all inherited classes can introduce extra functionality without having to change the delegate signature. They can simply introduce a new event class (ExtendedEventArgs
) which inherits yours (SomeEventArgs
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With