Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

  • What is the difference between the two ways to call the Action, if any?

  • Is one better than the other?

  • When use which?

Thanks

like image 333
labroo Avatar asked Oct 26 '11 18:10

labroo


People also ask

What are Action delegates?

Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. For example, the following delegate prints an int value.

What is action in Linq?

LINQ in Action is a fast-paced, comprehensive tutorial for professional developers who want to use LINQ. This book explores what can be done with LINQ, shows you how it works in an application, and addresses the emerging best practices.

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.


1 Answers

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)

like image 130
SLaks Avatar answered Oct 05 '22 16:10

SLaks