3

Suppose I have some delegate in C#:

public delegate void ExampleDelegate();

and somewhere I have SampleMethod which I want the delegate to reference:

ExampleDelegate sample = new ExampleDelegate(SampleMethod);

What I've seen some people do in 2 lines instead is this:

ExampleDelegate sample;
sample = SampleMethod;

Is this the same like the line above in terms of functionality or is there some (unintended) side effect going on? Basically, I don't understand the difference between:

ExampleDelegate sample = new ExampleDelegate(SampleMethod);

and

ExampleDelegate sample; = SampleMethod;

They seem to be working the same..

daremkd
  • 8,244
  • 6
  • 40
  • 66

2 Answers2

4

There is no difference, they are the same. The second is an implicit method group conversion.

This syntax was introduced in C# 2.0 and is covered in the programming guide in How to: Declare, Instantiate, and Use a Delegate.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
2

There is no difference they produce exactly the same cil code.

For example. given following c# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    public delegate void ExampleDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            ExampleDelegate sample1 = new ExampleDelegate(SampleMethod);
            ExampleDelegate sample2 = SampleMethod;
        }

        static void SampleMethod()
        {

        }
    }
}

This is the cil code of the main method:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       28 (0x1c)
  .maxstack  2
  .locals init ([0] class ConsoleApplication6.ExampleDelegate sample1,
           [1] class ConsoleApplication6.ExampleDelegate sample2)
  IL_0000:  nop
  IL_0001:  ldnull
  IL_0002:  ldftn      void ConsoleApplication6.Program::SampleMethod()
  IL_0008:  newobj     instance void ConsoleApplication6.ExampleDelegate::.ctor(object,
                                                                                native int)
  IL_000d:  stloc.0
  IL_000e:  ldnull
  IL_000f:  ldftn      void ConsoleApplication6.Program::SampleMethod()
  IL_0015:  newobj     instance void ConsoleApplication6.ExampleDelegate::.ctor(object,
                                                                                native int)
  IL_001a:  stloc.1
  IL_001b:  ret
} // end of method Program::Main
Jesús López
  • 8,338
  • 7
  • 40
  • 66