Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action<T> vs delegate event

Tags:

c#

delegates

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)); } 
like image 329
Bhaskar Avatar asked Feb 17 '10 16:02

Bhaskar


People also ask

What is the difference between delegate and event?

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.

What does it mean to be a delegate at an event?

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.

What is action t used for in an application?

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.

What Is an Action 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.


1 Answers

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.

like image 55
Hans Passant Avatar answered Sep 20 '22 18:09

Hans Passant