C # delegate: constructor literal
Suppose I have a delegate in C #:
public delegate void ExampleDelegate();
and somewhere I have a SampleMethod that I want the delegate to reference:
ExampleDelegate sample = new ExampleDelegate(SampleMethod);
What I saw, for example, from some people in two lines, looks like this:
ExampleDelegate sample; sample = SampleMethod;
Is this the same as the line above in terms of functionality, or is there some (unintended) side effect? Basically, I don't understand the difference between:
ExampleDelegate sample = new ExampleDelegate(SampleMethod);
and
ExampleDelegate sample; = SampleMethod;
They seem to work the same way.
+3
source to share
2 answers
There is no difference, they are the same. The second is the implicit conversion of the method group.
This syntax was introduced in C # 2.0 and is described in the programming guide at How to Declare, Create, and Use a Delegate .
+4
source to share
It makes no difference that they produce exactly the same cil code.
For example. given the 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
+2
source to share