Difference between Delegate.Invoke and Delegate()

Delegate.Invoke and Delegate() are identical. both do the same thing . see the bellow code

static async Task Main(string[] args)
{
   MyDelegate mydelegate = new MyDelegate(CallMe);
   mydelegate.Invoke("Reza");
   mydelegate("Reza");
}

public delegate void MyDelegate(string message);
public static void CallMe(string message)
{
}

IL

IL_001a: ldarg.0
IL_001b: ldfld class TestConsole.Program/MyDelegate TestConsole.Program/'<Main>d__1'::'<mydelegate>5__1'
IL_0020: ldstr "Reza"
IL_0025: callvirt instance void TestConsole.Program/MyDelegate::Invoke(string)
IL_002a: nop
IL_002b: ldarg.0
IL_002c: ldfld class TestConsole.Program/MyDelegate TestConsole.Program/'<Main>d__1'::'<mydelegate>5__1'
IL_0031: ldstr "Reza"
IL_0036: callvirt instance void TestConsole.Program/MyDelegate::Invoke(string)
IL_003b: nop

I usually use Invoke() because you can use the null-check and people reading through the code can more easily see that a delegate is being use.

null-check

MyDelegate mydelegate = null;
mydelegate?.Invoke("Reza");
mydelegate("Reza"); // Error: System.NullReferenceException

That's correct. Both have the exact same result.

Given that you have properly initialized delTest of course.


The delTest() form is a compiler helper, underneath it is really a call to Invoke().


Richard's answer is correct, however starting with C# 6.0, there is one situation where using Invoke() directly could be advantageous due to the addition of the null conditional operator. Per the MS docs:

Another use for the null-conditional member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:

var handler = this.PropertyChanged;
if (handler != null)  
    handler(…);

The new way is much simpler:

PropertyChanged?.Invoke(…)   

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in a temporary variable. You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e).

Tags:

C#

Delegates