I am getting ready to create a generic EventArgs class for event args that carry a single argument:
public class EventArg<T> : EventArgs { // Property variable private readonly T p_EventData; // Constructor public EventArg(T data) { p_EventData = data; } // Property for EventArgs argument public T Data { get { return p_EventData; } } }
Before I do that, does C# have the same feature built in to the language? I seem to recall coming across something like that when C# 2.0 came out, but now I can't find it.
Or to put it another way, do I have to create my own generic EventArgs class, or does C# provide one? Thanks for your help.
EventArgs is also the class you use when an event does not have any data associated with it. When you create an event that is only meant to notify other classes that something happened and does not need to pass any data, include the EventArgs class as the second parameter in the delegate. You can pass the 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.
Firing an event is a one-way signal. By default most event handlers return void , because single event may have several subscribers, and return value could become ambiguous. However, it is possible for handlers to return values.
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
No. You probably were thinking of EventHandler<T>
, which allows you to define the delegate for any specific type of EventArgs.
I personally don't feel that EventArgs<T>
is quite as good of a fit, though. The information used as a "payload" in the event args should be, in my opinion, a custom class to make its usage and expected properties very clear. Using a generic class will prevent you from being able to put meaningful names into place. (What does "Data" represent?)
I must say I don't understand all the 'purists' here. i.e. if you already have a bag class defined - which has all the specifics, properties etc. - why the hack create one extra unnecessary class just to be able to follow the event/args mechanism, signature style? thing is - not everything that is in .NET - or is 'missing from' for that matter - is 'good' - MS's been 'correcting' itself for years... I'd say just go and create one - like I did - cause I needed it just like that - and saved me lot of time,
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