In class's derived from a Component I sometimes see events declared like:
private static readonly object LoadEvent = new object();
public event EventHandler<MyEventArgs> Load
{
add { Events.AddHandler(LoadEvent, value); }
remove { Events.RemoveHandler(LoadEvent, value); }
}
protected virtual void OnLoad(MyEventArg e)
{
var evnt = (EventHandler<MyEventArg>)Events[LoadEvent];
if (evnt != null)
evnt(this, e);
}
Instead of just:
public event EventHandler<MyEventArgs> Load;
protected virtual void OnLoad(MyEvent e)
{
if (Load != null)
Load(this, e);
}
I'm tempted to to refactor to use the shorter method, but I am hesitant in case there are some advantages to using the Component EventHanderList that I am missing.
The only advantages I can currently think of are:
Is there anything else?
(This is not a question about the general use of explicit add + removes on events.)
The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. You simply provide the type of the event data object as the generic parameter.
A delegate is a way of telling C# which method to call when an event is triggered. For example, if you click a Button on a form, the program would call a specific method. It is this pointer that is a delegate. Delegates are good, as you can notify several methods that an event has occurred, if you wish so.
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.
Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events. An event is dependent on a delegate and cannot be created without delegates.
This is good for sparse events. UI controls tend to have dozens (sometimes upwards of 100) events. If a field-like-event was used for each, then each event requires a reference backing-field. With 100 events, that is 400 bytes on x86 or 800 bytes on x64, even if not a single event is subscribed.
As an example, a winforms System.Windows.Forms.Form
has 91 events before you've added any. Every single Control
instance has at least 69.
So; a windows form with a few labels, input boxes and buttons could easily have an extra 2000 reference fields (16k on x86) most of which are doing nothing.
The EventHandlerList
is essentially a key/value lookup, which means that if only 3 events are subscribed (I'm thinking "Click" and maybe a few others) then only a nominal amount of memory is required.
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