labroo
labroo

Reputation: 2961

Difference between Action(arg) and Action.Invoke(arg)

static void Main()
{
    Action<string> myAction = SomeMethod;

    myAction("Hello World");
    myAction.Invoke("Hello World");
}

static void SomeMethod(string someString)
{
    Console.WriteLine(someString);
}

The output for the above is:

Hello World
Hello World

Now my question(s) is

Thanks

Upvotes: 46

Views: 10596

Answers (1)

SLaks
SLaks

Reputation: 887657

All delegate types have a compiler-generated Invoke method.
C# allows you to call the delegate itself as a shortcut to calling this method.

They both compile to the same IL:

C#:

Action<string> x = Console.WriteLine;
x("1");
x.Invoke("2");

IL:

IL_0000:  ldnull      
IL_0001:  ldftn       System.Console.WriteLine
IL_0007:  newobj      System.Action<System.String>..ctor
IL_000C:  stloc.0     
IL_000D:  ldloc.0     
IL_000E:  ldstr       "1"
IL_0013:  callvirt    System.Action<System.String>.Invoke
IL_0018:  ldloc.0     
IL_0019:  ldstr       "2"
IL_001E:  callvirt    System.Action<System.String>.Invoke

(The ldnull is for the target parameter in an open delegate)

Upvotes: 54

Related Questions