title: What is the difference between a delegate instance and a method pointer?
body: <p>I thought that a delegate instance was interchangeable with a function instance.</p>
  
  <p>Take the following code:</p>
  
  <pre><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());
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Is there someone out there that knows what the difference is?</p>