2

Possible Duplicate:
very simple delegate musing

I've been wondering what's the difference between this method of defining a delegate

System.Action act;
act = MethodWithoutParameters;

and this one

System.Action act;
act = new System.Action(MethodWithoutParameters);

. Should I prefer one over the other? If so, why? I have unfortunately not been able to find much information regarding my question. I'd really appreciate it if someone could tell me the differences between those two pieces of code.

Community
  • 1
  • 1
haiyyu
  • 2,194
  • 6
  • 22
  • 34

3 Answers3

6

It's syntactic sugar: an "implicit method group conversion". The compiler transforms the first version into the second.

phoog
  • 42,068
  • 6
  • 79
  • 117
4

These two pieces of code produce the exact same IL. There is no reason to prefer one over the other. It is simply a matter of style.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

It's exatcly the same, there is no difference

I would add also the third one, lambda !:

System.Action act = x=>DoSomething(x);
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 3
    That one is slightly different. It introduces a lambda expression, making the delegate point to a method which in turn calls the DoSomething method. There are several (admittedly obscure) cases where this is functionally different. – Chris Shain Jan 04 '12 at 22:13
  • @ChrisShain: If this could be different, so declaring the same `lambda` inside ordinary function declared like a `delegate` *should* lead to same obscure results. Isn't it? – Tigran Jan 04 '12 at 22:16
  • I'm not sure I understand what you are asking – Chris Shain Jan 04 '12 at 22:34
  • I mean, why this example would be different from those ones presented before, if I put **this** lambda notion inside a function. Like, for example `act = MethodWithoutParameters` inside `MethodWithoutParameters` I have a lambda call `x=>DoSomething(s);` ? – Tigran Jan 04 '12 at 22:36
  • Passing parameters makes no difference, if that's what you mean. – Chris Shain Jan 04 '12 at 22:53
  • One functional difference between the lambda and non-lambda version is caching. In certain cases the C# compiler will cache the result of a lambda expression as a static field. It will never cache either of the two cases in the question. – JaredPar Jan 04 '12 at 23:08
  • @JarerPar: Guys, sure: there is a cashing, there is a lazy evaluation, but from *this question* perspective it doesn't change too much. I mean if I go in search of possible trouble, I can find them also in ordinary methods implementation too. The question is not: "which one is faster", "more portable", "consumes less memory", but what is the `behavioral` difference *apart* from the context where it used. At least, *I*, understand it in this way. – Tigran Jan 04 '12 at 23:13