IDisposable Interface in C#

This article about the IDisposable pattern is the continuation of my previous article “Object LifeTime in .NET Framework".

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on. This method is implemented explicitly in the code when we need to clean up a disposable object and to release unmanaged resources that this disposable object holds.

The following is an implementation of IDisposable in a class:

IDisposable in a class

There are few things to notice in the code:

  • ~DisposableClass()

    We can identify it is a destructor method by the symbol ~ (tilde). It is actually converted into a Finalize method because in C# the compiler translates the destructor to a Finalize() method. Please see the following figure showing the Finalize method in the ildasm.exe tool for the destructor ~DisposableClass (that is defined in the preceding sample code).

    DisposableClass

    The question would be: Why we are using the Finalize method if we are already using the Dispose method in the code to clean up managed resources?

    The answer is: The Dispose method is implemented explicitly by the programmer and there is the chance that the programmer fails or forgets to dispose of the unmanaged resources, so the Finalize method should be called for a safer side to prevent a memory leak. If the Dispose method is not called for any reason then the destructor would be called by the garbage collector, but when the Finalize method would be called by the garbage collector is not determined. The garbage collector can call it anytime there is a requirement of more memory or when the program exits or anytime on some other conditions.

  • GC.SuppressFinalize()

    If the Dispose method is called then there is no need of the Object. The Finalize() override method is to be called by the garbage collector and that Dispose() that is implemented explicitly in the code would clean up all the unmanaged resources. That is why the GC. SuppressFinalize() method is called to prevent the garbage collector from running the finalizer.

    Both the Finalize and Dispose methods are used to destroy unmanaged resources. Finalize has performance issues since it is called by the garbage collector and as I said earlier, when the Finalize method will be called by the garbage collector is not specified.

    The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement.
    1. using (TextWriter txt= File.CreateText (“myfile.txt”)  
    2. {  
    3.    txt.WriteLine (“Comments Started :”);  
    4. }  
    You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.

I hope this article will be helpful for you. Your feedback and suggestions are always welcomed.