0

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?

Ricardo Zorio
  • 282
  • 5
  • 11

3 Answers3

2

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
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
2

Absolutely nothing. The compiler will convert the second one into an instantiation of Delegate just like the first one:

// Delegate del = new Delegate(foo);
ldftn    void App.Program::foo()
newobj   instance void App.Program/Delegate::.ctor(object, native int)
stloc.0

// Delegate de2l = foo;
ldftn    void App.Program::foo()
newobj   instance void App.Program/Delegate::.ctor(object, native int)
stloc.1
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
1

Nothing to my knowledge. The compiler will generate the new for you. A similar question was answered here. This shortcut method was introduced from C# 2.0 onwards - MSDN.

Community
  • 1
  • 1
Fuzzyllama
  • 23
  • 3