Search code examples
c#delegatesinstantiation

C# delegate instantiation syntax


I have seen different forms of instantiating a delegate object. For example:

I have the following delegate and method.

public delegate void Delegate();
public void foo();

And these two options for instantiation.

Delegate del = new Delegate(foo);
Delegate del = foo;

My question is as follows: What is the semantic difference between these two statements?


Solution

  • The short answer is none.

    The long answer is, they both compile to the same IL.

    Delegate del1 = foo;
    Delegate del2 = new Delegate(foo);
    

    compiles to

    IL_0001:  ldarg.0     
    IL_0002:  ldftn       UserQuery.foo
    IL_0008:  newobj      UserQuery+Delegate..ctor
    IL_000D:  stloc.0     // del1
    IL_000E:  ldarg.0     
    IL_000F:  ldftn       UserQuery.foo
    IL_0015:  newobj      UserQuery+Delegate..ctor
    IL_001A:  stloc.1     // del2