Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing event arguments in a class, why?

Tags:

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?

like image 507
Daniel Mošmondor Avatar asked Nov 25 '11 14:11

Daniel Mošmondor


People also ask

What are event arguments?

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.

What base class do you use to convey information for an event?

EventArgs is a base class for conveying information for an event.

Which class should be inherited when a class for custom event argument is written?

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 .

What is EventArgs in VB?

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.


1 Answers

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).

like image 115
jgauffin Avatar answered Oct 23 '22 19:10

jgauffin