Bali C
Bali C

Reputation: 31231

Do you need to use Invoke on Action?

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

Upvotes: 3

Views: 441

Answers (2)

Habib
Habib

Reputation: 223287

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(...);
    // ...
}

Upvotes: 5

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

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.

Upvotes: 4

Related Questions