2

I was looking around for an answer to this but couldn't find anything related. I have learnt to use Action.Invoke() when using an Action, but do you actually need to use .Invoke?

Say I have this Action:

Action<int> action = x =>
{
    Console.WriteLine(x + 1);
};

Do I use:

action.Invoke(2);

or

action(2);

What's the difference?

Thanks

Bali C
  • 30,582
  • 35
  • 123
  • 152

2 Answers2

5

Its the same thing, action(2); basically calls action.Invoke(2);
The compiler converts action(2) into action.Invoke(2);

From a post from Jon Skeet:

Personally I typically use the shortcut form, but just occasionally it ends up being more readable to explicitly call Invoke. For example, you might have:

if (callAsync)
{
    var result = foo.BeginInvoke(...);
    // ...
}
else
{
    foo.Invoke(...);
    // ...
}
Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
3

The latter is purely syntactic sugar for the former - there is no difference (both are also synchronous).

It is nice to just be able to run the action like a method instead of the intermediary Invoke call.

Invoke has a counterpart BeginInvoke for asynchronous invocation.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187