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