title: C# calling IDisposable.Dispose() vs making object null
body: <p>Consider the following code:</p>
  
  <p>A. Toy Class</p>
  
  <pre><code>class Toy
  {
      private string name;
      public string Name
      {
          get { return name; }
          set { name = value; }
      }
  
      private ToyAddon addOn;
      public ToyAddon AddOn
      {
          get { return addOn; }
          set { addOn = value; }
      }
  
      public void RemoveAddons()
      {
          /*
           * someone said: this could lead to possible memory leak
           * if this class implements IDisposable,
           * then we are not disposing any of the resource 
           * */
          //this.addOn = null; 
  
          /* instead use this */
          var disposableToyAddOn = this.addOn as IDisposable;
          if (disposableToyAddOn != null)
              disposableToyAddOn.Dispose();
  
          this.addOn = null;
  
      }
      public override string ToString()
      {
          return String.Format("{0}, {1}",
              this.name, 
              (this.AddOn == null) ? "" : addOn.AddOnName);
      }
  }
  </code></pre>
  
  <p>B. Toy Addon</p>
  
  <pre><code>class ToyAddon
  {
      private string addOnName;
  
      public string AddOnName
      {
          get { return addOnName; }
          set { addOnName = value; }
      }
  
  }
  </code></pre>
  
  <p>C. Main Program</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          ToyAddon tAdd = new ToyAddon();
          tAdd.AddOnName = "Amazing AddOn";
          Toy t = new Toy();
  
          t.Name = "Amazing Toy";
          t.AddOn = tAdd;
          t.RemoveAddons();
  
          Console.WriteLine(t.ToString());
  
  
      }
  }
  </code></pre>
  
  <p>Now it was suggested to me that check if a "having-a" object is implementing IDisposable then call the dispose method of it.
  (please check the comments in Toy class)</p>
  
  <p>IMHO, if I make the reference null, then the object on heap would be marked for Collection by GC.</p>
  
  <p><strong><em>It would be appreciated if this reasoning can be made on, what happens on heap and stack, and role of GC in that if the class (as ToyAddOn ) implements IDisposable vs if it does not.</em></strong></p>