I have seen developers using the below codes quite alternatively. What is the exact difference between these, and which ones go by the standard? Are they same, as Action
and Func<T>
is a delegate as well:
public event Action<EmployeeEventAgs> OnLeave;
public void Leave()
{
OnLeave(new EmployeeEventAgs(this.ID));
}
VS
public delegate void GoOnLeave(EmployeeEventAgs e);
public event GoOnLeave OnLeave;
public void Leave()
{
OnLeave(new EmployeeEventAgs(this.ID));
}
You may want to look here, seeing what the compiler actually generates for Action is the best description. There's no functional difference in what you wrote, just shorter, more convenient syntax.
The following two lines of code are almost equivalent:
compared to:
The difference is in the signature of the event handler method. If you use the first approach with the action, you could have:
and then this:
With the second approach, the signature of the
LeaveHandler
needs to be different:It is very important to notice that in both cases the
event
keyword is used to declare the event member. An event member declared this way is not simply a field of the class, despite it looks as if it was. Instead, the compiler creates it as an event property1. The event properties are similar to regular properties, except that they do not haveget
orset
accessors. The compiler allows them to be used only on the left side of a+=
and-=
assignments (adding or removing an event handler). There is no way to overwrite the already assigned event handlers, or to invoke the event outside the class that declares it.If the event keyword was missing in both examples, you could do the following operations with no error or warning:
which will erase any registered handlers and replace them withe the
LeaveHandler
.In addition, you can also perform this call:
The two situations above are considered an anti-pattern, if you intend to create an event. An event should be invoked only by the owner object and should not allow for untraceable removal of subscribers. The
event
keyword is the .NET's programmatic construct that helps you stick with the correct use of events.Having the above in mind, I believe many people stick to the
EventHandler
approach because it is more unlikely to use anEventHandler
without theevent
keyword. Actions have wider scope of usage, they do not look as naturally when used as events. The latter is, of course, a personal opinion, as the event handler approach has probably become too hardwired in my own coding practices. Still, if actions are used properly, it is not a crime to use them for events.1 An event property is what the compiler automatically generates when seeing code like this:
It becomes roughly the same code as the following:
Event invocations which we write as this:
are converted into this: