title: Should I dispose old object before assigning new object?
body: <p>Lets assume we have two class <strong>Foo</strong> and <strong>Bar</strong> as given below.</p>
  
  <pre><code>public class Foo
  {
      public static Bar BarInstance { get; set; }
  
      public static void Main()
      {
          AssignBar("A");
          AssignBar("B");
      }
  
      private static void AssignBar(string name)
      {
          BarInstance = new Bar(name);
      }
  }
  
  public class Bar : IDisposable
  {
      public Bar(string name)
      {
          Name = name;
      }
      public string Name { get; set; }
      protected virtual void Dispose(bool disposing)
      {
          if (!disposing)
          {
              return;
          }
      }
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }
  }
  </code></pre>
  
  <p>When object A gets replaced by object B. I expect <code>Dispose</code> to called because since there is no reference to Object A exists any more, but it doesn't get called. Could you please explain why?</p>
  
  <p>Should I end up doing <code>CurrentBar.Dispose</code> like below if I want Object A to be disposed.</p>
  
  <pre><code>    private static void AssignBar(string name)
      {
          if (BarInstance != null)
          {
           BarInstance.Dispose();   
          }
          BarInstance = new Bar(name);
      }
  </code></pre>