Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using Action.Invoke considered best practice?

Tags:

c#

.net

delegates

If I have the below code, should I just call the Action or should it call Action.Invoke?

public class ClassA {   public event Action<string> OnAdd;    private void SomethingHappened()   {     if (OnAdd != null)      OnAdd("It Happened"); //Should it be OnAdd.Invoke("It Happened") ???????   } }  public class ClassB {    public ClassB()   {     var myClass = new ClassA();     myClass.OnAdd += Add;   }    private void Add(string Input)   {     //do something   }   } 
like image 294
Jon Avatar asked Feb 13 '12 11:02

Jon


2 Answers

The two are equivalent, the compiler converts OnAdd("It Happened"); into OnAdd.Invoke("It Happened"); for you.

I guess it's a matter of preference, however I personally prefer the terser form.

As an aside, it is generally preferable to take a local copy of a class level delegate before invoking it to avoid a race condition whereby OnAdd is not null at the time that it is checked, but is at the time that it is invoked:

private void SomethingHappened() {   Action<string> local = OnAdd;   if (local != null)   {     local("It Happened");   } } 
like image 120
Rich O'Kelly Avatar answered Oct 04 '22 16:10

Rich O'Kelly


Something I noticed on this with the latest C# 6 release as it may encourage Invoke to be used more and thought I'd add it to this old question in case it helps someone:

"Old" way:

Action<string> doSomething = null; // or not null if (doSomething != null)     doSomething("test"); 

Possible pragmatic way (similar to empty event delegate pattern):

Action<string> doSomethingPragmatic = s => { }; // empty - might be overwritten later doSomethingPragmatic("test"); 

C# 6:

Action<string> doSomethingCs6 = null; // or not null doSomethingCs6?.Invoke("test");  // Not valid C#: // doSomethingCs6?("test") // doSomethingCs6?.("test") 
like image 27
jamespconnor Avatar answered Oct 04 '22 16:10

jamespconnor