IDisposable interface in C#.

Often in our application development we need to acquire and release some resources. That unmanaged resources could be files that we want to use from time to time, database connections, fonts etc. The important thing is to release resources once we have done with it. Since the CLR  uses Garbage Collection to manage lifecycle of objects created on the heap, it is not possible to control the release and recovery of heap objects. Even with GC it is not guaranteed to clear all objects and it’s highly inefficient for an application to force garbage collector clean that things up.

Using the object in a using block, the resource release will be done automatically.


TextReader textReader = null;

try
{
    using (textReader = new StreamReader(@"Files\sample.txt"))
    {
        string str = textReader.ReadToEnd();

        Console.WriteLine(str);
    }
}
catch (Exception ex)
{}

You probably already know, that using helps us work with an object that implements IDisposable interface. The using statement ensures that Dispose is called.  So, in some cases when your class uses unmanaged resources and you want to be able to use using keyword to dispose resources you need to implement IDisposable interface. Here is the example of implementation:

public class MyDisposableObj :
    IDisposable
{
    bool _disposed;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyDisposableObj()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
        {
            // free other managed objects that exist in this class 
            // that implement IDisposable only
        }

        // release any unmanaged objects
        // set the object references to null

        _disposed = true;
    }
}
Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this