0
using System; 

delegate void D(int x); 

class C 
{ 
   public static void M1(int i) { 
    Console.WriteLine("C.M1: " + i); 
   } 
}

  D cd1 = new D(C.M1);
  D cd2 = C.M1;

Delegate instances cd1 and cd2 are created differently above.

Are they equivalent?

If not, what differences are between them?

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590
  • maybe same [question](http://stackoverflow.com/questions/550703/c-difference-between-anevent-and-new-eventhandleranevent) – Lei Yang Mar 31 '17 at 02:24

2 Answers2

4

If you look at the IL generated via a tool like LinqPad, you would find that in this case both blocks compile to the exact same thing:

void Main()
{
    D cd1 = new D(C.M1);
    D cd2 = C.M1;
}

becomes

IL_0000:  nop         
IL_0001:  ldnull      
IL_0002:  ldftn       UserQuery+C.M1
IL_0008:  newobj      UserQuery+D..ctor
IL_000D:  stloc.0     // cd1
IL_000E:  ldnull      
IL_000F:  ldftn       UserQuery+C.M1
IL_0015:  newobj      UserQuery+D..ctor
IL_001A:  stloc.1     // cd2
IL_001B:  ret  

Note that instructions are 2-5 are repeated in 6-9, with a different stloc since a new instance is created.

David L
  • 32,885
  • 8
  • 62
  • 93
4

Are they equivalent?

Yes. Delegates created explicitly and delegates created using the Method Group Syntax are equivalent to each other.

Method Group Conversion has been introduced in C# 2.0. In the first version of C# the syntax that you used for cd1 was the only choice available for creating a delegate.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523