37

May be this question asked earlier ,i did googling but i didnt get answer.

Delegate Prototype

delegate void method1(string str);

Adding Callback methods

method1 objDel2;           
objDel2 = new method1(TestMethod1);            
objDel2("test");
objDel2.Invoke("Invoke");

In Above coding objDel2("test"); and objDel2.Invoke("Invoke"); are doing same task.Which one is good or both are same .

Prabhakaran Parthipan
  • 4,193
  • 2
  • 18
  • 27
  • 1
    Are you asking if `bjDel2("test");` and `objDel2.Invoke("Invoke");` are the same? Yes, they are. Or are you asking which one should be preferred? That's primarily opinion-based. – dtb Aug 28 '13 at 12:29
  • Its one and the same the difference is just calling invoke explicitly – Rohit Aug 28 '13 at 12:34

1 Answers1

61

They are 100% identical - this is pure compiler sugar (see below). As for which is preferred: neither / both.

static class Program {

    static void Main()
    {
        method1 objDel2;
        objDel2 = new method1(TestMethod1);
        objDel2("test");
        objDel2.Invoke("Invoke");
    }
    delegate void method1(string val);
    static void TestMethod1(string val) {
        System.Console.WriteLine(val);
    }
}

has the IL

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 2
    .locals init (
        [0] class Program/method1 'method')
    L_0000: ldnull 
    L_0001: ldftn void Program::TestMethod1(string)
    L_0007: newobj instance void Program/method1::.ctor(object, native int)
    L_000c: stloc.0 
    L_000d: ldloc.0 
    L_000e: ldstr "test"
    L_0013: callvirt instance void Program/method1::Invoke(string) ***HERE***
    L_0018: ldloc.0 
    L_0019: ldstr "Invoke"
    L_001e: callvirt instance void Program/method1::Invoke(string) ***HERE***
    L_0023: ret 
}

Note both do the same thing (see the two locations marked by me as ***HERE***)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 38
    In C#6 using `Invoke` has one advantage, you can use the null propagation operator to avoid the necessary null-check: `objDel2?.Invoke("Invoke");`. You can't write `objDel2?("test");` – Tim Schmelter Jul 28 '16 at 08:25
  • 1
    @TimSchmelter yup, and it is awesome for invoking events without having to do the "snapshot, test, invoke" triple – Marc Gravell Jul 28 '16 at 11:58
  • @MarcGravell, Where you get IL code? Is there any tool available? – RGS Jul 08 '17 at 14:50
  • 2
    @RGD "ildasm" is installed as default with Visual Studio or the .NET SDK. There are also tools like .NET Reflector, but that isn't free. "ildasm" is often enough. – Marc Gravell Jul 08 '17 at 17:21
  • 4
    @RGS https://sharplab.io/ is also useful when you want to see IL for code snippets – Menyus Jun 13 '22 at 20:54