I thought that a delegate instance was interchangeable with a function instance.
Take the following code:
delegate int AddDelegate(int a, int b);
AddDel
Delegates are classes that are callable, and have similar behavior to function pointers. The delegate internally stores the address of the function to call (i.e. the function pointer), but also provides other functionality such as multi-casting and storing an invocation list; you can essentially invoke many functions of the same signature with one delegate instance as follows.
public void DoStuff()
{
DelegateInstance += Add;
DelegateInstance += AnotherAdd;
DelegateInstance += YetAnotherAdd;
// Invoke Add(100, 200), AnotherAdd(100, 200), and YetAnotherAdd(100, 200)
DelegateInstance(100, 200);
}
Regarding your note about the equivalence of MethodThatTakesAdd(Add)
and MethodThatTakesAdd(DelegateInstance)
,
if you look at the MSIL that the C# compiler generates for the line MethodThatTakesAdd(Add)
, you will notice that the compiler is creating a delegate and wrapping the Add()
method for you.