Suppose we have two classes Foo and Bar , as shown below.
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);
}
}
When Object A is replaced by Object B. I expect it to Disposebe called, because since the reference to Object A no longer exists, it is not called. Could you explain why?
Do I have to finish execution CurrentBar.Disposeas shown below if I want Object A to be deleted.
private static void AssignBar(string name)
{
if (BarInstance != null)
{
BarInstance.Dispose();
}
BarInstance = new Bar(name);
}
source
share