Should I delete an old object before assigning a new object?

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);
    }
+4
source share
3 answers

It depends on ownership.

Is Bargiven Foowith the implication that Foonow belongs Bar?

, , Dispose , .

Bar Foo, , , .. , - ?

, , Dispose , .


, , .

, 3 :

  • Foo Bar. , Bar - , .
  • Foo Bar. , , . , , .
  • Foo Bar , , , . , , Foo Bar , true .

Dispose - , # , , .

, , - , , . , , , , Dispose.

+3

Dispose . . .

private static void AssignBar(string name)
{
    if(BarInstance!=null)
    {
        BarInstance.Dispose();
    }
    BarInstance = new Bar(name);
}

, IDisposable. ( ). DisposablePattern, Dispose(bool), . GC .

+3

Dispose , . , , . .

, using:

using(var x = new BarInstance())
{
  // Whatever
}

. , , Dispose, .

You can select a finalizer in your class ~Bar. In the finalizer, you can manage any resources that you hold. However, when the finalizer will be called in a non-deterministic state, it is even possible that it will never be called if the garbage collector does not start.

+2
source

All Articles