5

Possible Duplicate:
Why use “new DelegateType(Delegate)”?
What is the difference between new Thread(void Target()) and new Thread(new ThreadStart(void Target()))?

So I have been through a little bit of delegate and got the whole idea somehow. Now, I see everywhere exemple like this:

public delegate void Deleg();
Deleg deleg = new Deleg(FunctionName);

deleg();

I would think this creates an delegate object with the function to point at being passed as parameter to the constructor.

Now, I can also do like this:

public delegate void Deleg();
public Deleg deleg;  

deleg = FunctionName;
deleg();

This one seems to only create a reference and the address of the function is passed. This works just the same and has all the delegate functionalities.

But now, regardless of the fact I have one more line in the second exemple, do I actually lose or gain something out of the second since the first one is more popular on tutorials?

Community
  • 1
  • 1
Everts
  • 10,408
  • 2
  • 34
  • 45

3 Answers3

5

The gain is a little less typing. The compiler is smarter now than it was initially, so it can do the method group conversion implicitly which is why you don't have to do new Deleg(FunctionName) anymore.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • Ok, thanks for that, I was asking as I do not have the visual studio command prompt on this computer to look at the IL. – Everts Jan 05 '13 at 20:24
0

If you add the assignment on the same line (as you do in the first examaple), then the amount of code you type is about the same.

public delegate void Deleg();
public Deleg deleg = FunctionName;
deleg();
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

Second is delegate inference.

Does the method match with delegate's input parameter list in order and type?

  • Yes -> The delegate is inferred because the method signature matches the delegate's one.

  • No -> The delegate and method input parameters doesn't match. No delegate type inference is possible.

Do you lose something using delegate type inference? No. It's the same thing and I would argue that's preferable: less verbose code and it improves readability.

In addition, delegate type inference adds another option for you:

public delegate void Do();

Do some = () =>
{
   // Do stuff
};

Or

public delegate void Do(string a, string b);

// C# compiler infers the delegate from the lambda/anonymous method signature and it infers the type of the whole parameters too!
Do some = (a, b) =>
{
   // Do stuff
}
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206