Question:
I'm working in C# and I had a little doubt.
Is there a difference between calling a delegate directly or using the Invoke
method?
For example:
Func<string> @Func = () => "Test";
var result = @Func.Invoke();
var result2 = @Func();
Console.WriteLine("{0},{1}",result,result2);
// El resultado es Test,Test
Is there a difference between the line @Func.Invoke();
and @Func();
?
If there is such a difference, in what cases should each be used?
Answer:
In these cases, it is best to see what the compiler does when it converts the code to IL:
IL_0001: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0006: brtrue.s IL_001B
IL_0008: ldnull
IL_0009: ldftn b__0
IL_000F: newobj System.Func<System.String>..ctor
IL_0014: stsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0019: br.s IL_001B
IL_001B: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0020: stloc.0 // Func
IL_0021: ldloc.0 // Func
IL_0022: callvirt System.Func<System.String>.Invoke
IL_0027: stloc.1 // result
IL_0028: ldloc.0 // Func
IL_0029: callvirt System.Func<System.String>.Invoke
IL_002E: stloc.2 // result2
IL_002F: ldstr "{0},{1}"
IL_0034: ldloc.1 // result
IL_0035: ldloc.2 // result2
IL_0036: call System.Console.WriteLine
IL_003B: nop
IL_003C: ret
As you can see, the IL of @Func.Invoke()
is exactly the same as @Func()
:
callvirt System.Func<System.String>.Invoke
So both are exactly identical.