-1

As I know we use “Dispose” method of “IDisposable” interface when we want to release the unmanaged resources that the object uses them.

The destructor of the class (it is started with “~” character) is called automatically when the object is not usable anymore.

My question is: Why the destructor (finalize) of a class will not be fired when “GC.SuppressFinalize(this)” is used in “Dispose” method?

see the example No1, the destructor of the class (~ClassTest()) will be fired:

public class ClassTest : IDisposable
{
    public int PropA { get; set; }

    public ClassTest()
    {
        PropA = 10;
    }

    ~ClassTest()
    {
        Console.WriteLine("destructor");
    }

    public void Dispose()
    {
        Console.WriteLine("dispose");
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (ClassTest cT = new ClassTest())
        {
        }
    }
}

see the example No2, the destructor of the class (~ClassTest()) will NOT be fired:

public class ClassTest : IDisposable
{
    public int PropA { get; set; }

    public ClassTest()
    {
        PropA = 10;
    }

    ~ClassTest()
    {
        Console.WriteLine("destructor");
    }

    public void Dispose()
    {
        //it causes ~ClassTest() will not be fired, why?
        GC.SuppressFinalize(this);
        Console.WriteLine("dispose");
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (ClassTest cT = new ClassTest())
        {
        }
    }
}

I have seen an example of Microsoft MSDN that cause to ask this question: IDisposable Interface

Alireza
  • 170
  • 4
  • 17
  • @EugenePodskal No that's another question, that question does not focus on the destructor of a class. – Alireza Jan 08 '17 at 11:08
  • 1
    [Second answer](http://stackoverflow.com/a/3038973/3745022) in that question pretty much explains both how and why it happens. – Eugene Podskal Jan 08 '17 at 11:12
  • 3
    errr... because this is exactly the purpose of the `SuppressFinalize` method perhaps? ;) – Lucas Trzesniewski Jan 08 '17 at 11:13
  • @EugenePodskal Could you explain the technical reason of this behavior? so why we use destructor is this way? we could omit the destructor because it is not usable but Microsoft MSDN uses it in the example. – Alireza Jan 08 '17 at 11:15
  • @Alireza: when you call `SuppressFinalize`, you *avoid* using of destructor. In other words, you don't use it at all. The reason to suppress finalization is described in the referred question. – Dennis Jan 08 '17 at 11:19

1 Answers1

1

Unless there's a communication breakdown, the answer is in the method name: GC.SuppressFinalize. It suppresses, stops, finalization from being ran on the given object. Calling it in Dispose or anywhere else will have this effect.

kornman00
  • 808
  • 10
  • 27