I thought that a delegate instance was interchangeable with a function instance.
Take the following code:
delegate int AddDelegate(int a, int b);
AddDelegate DelegateInstance;
public void DoStuff()
{
//I can call this without a delegate "instance":
MethodThatTakesAdd(Add);
//I can also call it WITH a delegate "instance"
DelegateInstance = Add;
MethodThatTakesAdd(DelegateInstance);
}
public int Add(int a, int b)
{
return a + b;
}
public void MethodThatTakesAdd(AddDelegate addFunction)
{
Console.WriteLine(addFunction(1, 2).ToString());
}
Both ways of calling it APPEAR to be equivalent, and if you're using only C#, you'll never see the difference (at least I have not up to this point). However, I was recently unmanaged code that was calling back into this managed code, they are treated differently. For example, in one scenario, I to get the error "A callback was made on a garbage collected delegate" if I use the function directly as a callback (even though my object instance is kept around). Using the "delegate instance" fixes the problem.
Is there someone out there that knows what the difference is?