2

Possible Duplicate:
C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'

In C# .NET 3.5, the compiler doesn't care if I do this (assume ButtonClickHandler is a function):

button.OnButtonClicked += ButtonClickHandler;

or:

button.OnButtonClicked += new ButtonClickHandlerDelegate( ButtonClickHandler );

Are these functionally the same? I read the stackoverflow question below, but I'm not sure if it applies to this scenario as well:

The difference between implicit and explicit delegate creation (with and without generics)

Community
  • 1
  • 1
void.pointer
  • 24,859
  • 31
  • 132
  • 243
  • I voted to close my own question, since I can't delete it. stackoverflow's search is horrible so I was of course not able to find any of the useful questions you guys are linking to. – void.pointer Jul 11 '11 at 20:59

2 Answers2

3

Yes, the first is simply syntactic sugar for the latter. The compiler simply infers the type of the delegate and constructs it for you. The exact same IL will be emitted by the compiler.

The first, shorter and cleaner syntax (delegate inference - which I recommend you use for readability), was added in C#2 - that is why some designers (also Microsoft's) tend to use the long and more verbose syntax of newing the delegate.

Actually, I think this is a duplicate of this prior question.

Community
  • 1
  • 1
driis
  • 161,458
  • 45
  • 265
  • 341
  • Sorry for the duplicate. It's such a pain in the neck to find similar questions using stackoverflow's search. – void.pointer Jul 11 '11 at 20:42
  • Actually, thinking about it, I believe your question, is better than the previous one - it will be easier to find for people searching for the same question, because it includes more relevant words in the title (_delegate_, and _implicit_, namely). – driis Jul 11 '11 at 20:46
1

In C# 4 this will produce identical code, so yes they are functionally the same. In the first (shorter) form the compiler infers the delegate type from the method signature, which saves you the work having to do it explicitly.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335