2

I have two methods with the following signatures

void Invoke(Action method)
void Foo()

What is the difference between the following two lines of code?

Invoke(new Action(Foo));

and

Invoke(Foo);

and is the second line allowed?

Thanks

2
  • you might want to format your example a bit better. Nothing wrong, just for clarity's sake. Remember that if a question is clear and well-posed people will be more inclined to answer it. Beauty also helps (formatting, etc). Commented Dec 22, 2009 at 9:41
  • Correction: the first method should read as follows void Invoke(Action method) Now both lines will compile, but what is the difference between them? Thanks Commented Dec 22, 2009 at 10:14

2 Answers 2

3

Why don't you try it?

If the signature of your method is

void Invoke(Action objAction)

then it is legal. And then the 2 calls are the same. The feature for this is called "implicit method group conversion".

Sign up to request clarification or add additional context in comments.

Comments

2

Your signature is is "Invoke(Delegate method)" (capitalized 'D'), isn't it?

Only the first line constructing the Action explicitly works.

The reason behind this: Delegate is the base class for all delegates. It represents a delegate with an unknown return value and unknown number and type of parameters. You can only invoke it using DynamicInvoke.

So the compiler does not know, which actual type of delegate to use when passing only a method name: "Invoke(Foo);". It could be an Action, but also another delegate with the same signature as Foo.

However, if you explicitly create the delegate, it can be implicitly converted to Delegate and therefore the code compiles.

3 Comments

yeah that's exactly what I was typin up :) I think it's worth explaining how you know it's meant to be Delegate?
Well - if you use "delegate" instead of "Delegate" inside a method's parameter list, this will result in five compiler errors as "delegate" is a special keyword for defining delegates and for anonymous methods.
After the last edit (the signature is "void Invoke(Action method)") Maximilian Mayerl is right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.