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)); }
A delegate specifies a TYPE (such as a class , or an interface does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate.
A delegate is a person who is chosen to vote or make decisions on behalf of a group of other people, especially at a conference or a meeting.
You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.
Action delegate is an in-built generic type delegate. This delegate saves you from defining a custom delegate as shown in the below examples and make your program more readable and optimized. It is defined under System namespace.
Fwiw, neither example uses standard .NET conventions. The EventHandler<T>
generic should declare the event:
public event EventHandler<EmployeeEventArgs> Leave;
The "On" prefix should be reserved for a protected method that raises the event:
protected virtual void OnLeave(EmployeeEventArgs e) { var handler = Leave; if (handler != null) handler(this, e); }
You don't have to do it this way, but anybody will instantly recognize the pattern, understand your code and know how to use and customize it.
And it has the great advantage of not being forced to choose between a custom delegate declaration and Action<>
, EventHandler<>
is the best way. Which answers your question.
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