views:

25

answers:

3

When i have delegate like

public delegate void PrintMe();

(1)
PrintMe a = delegate() { MessageBox.Show("Hello"); };
a();

(2)
PrintMe b = () => { MessageBox.Show("Hello"); };
b();

(3)
PrintMe c = new PrintMe(HelpMe);
c();

static void HelpMe()
{
   MessageBox.Show("Help Me");
}

for (1) and (2) I did not instatntiate the delegate it is directly pointing to anonymous methods.But as in the case of (3) I need to instatntiate the delegate and pass the static method.for case (3) can't i declare like PrintMe c= HelpMe(); ?.How does (1) and (2) work?

+1  A: 
PrintMe c = HelpMe;
+3  A: 

Thanks to the implicit conversion between method groups and delegates you can say

(3)
PrintMe c = HelpMe;

i.e. without parenthesis

Thomas Wanner
Oops ! How fool I am!
+1  A: 

In (1) and (2) the compiler implicitly converts your lambda expression into a delegate.

If you try to do

PrintMe c= HelpMe();

then you are telling the compiler to generate a call to HelpMe and assign the result of that call to c. Instead, you can do

PrintMe c = HelpMe;

Here, HelpMe occours as what is known as a method group (it is not just a method, because it may have overloads), which may be converted to a delegate if at least one method in the group fits the delegate.

Rune