Make Disposing Objects Easier

As I talked about in my What’s the Purpose of the “using” Statement? post, disposing of your objects is very important in your application to prevent issues like virtual memory leaks. Equally important is as a developer of a type (class) that use any types that implements IDisposable, then your type must also implement IDisposable. Here is how I typically implement IDisposable in a class:

public class StudentsDataAccess : IDisposable
{
    private System.Data.Entity.DbContext _context;    
    ~StudentsDataAccess()
    {
        Dispose(false);
    }    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }    
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            this._context.Dispose();
        }
    }
}

The only issue that could arise with this code is that if _context is null, then calling Dispose will cause an Exception. But, as I have seen over and over again most developers don’t call Dispose anyway. So what if another disposable field is added to this class and the developer did not update the Dispose method, then this can cause issues. So, to eliminate this issue I wrote an extension method that will take care of this and the issue if the object is null. Here is the code:

public static class ObjectExtensions
{
    [System.Runtime.CompilerServices.Extension()]
    public static void DisposeFields(IDisposable obj)
    {
        var objs = obj.GetType().GetFields().Where(p => p.GetType()
                                                    .GetInterface(“IDisposable”) != null);
        objs.ForEach(p => TryDispose(p));
    }    
    [System.Runtime.CompilerServices.Extension()]
    public static void TryDispose(object obj)
    {
        if (obj == null)
        {
            return;
        }
        IDisposable disposable = obj as IDisposable;

        if (disposable == null)
        {
            return;
        }

        disposable.Dispose();
    }
}

The DisposeFields method above will find all the fields that are disposable for an object and then call Dispose using TryDispose. The first code example would need this easy modification:

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        this.DisposeFields();
    }
}

Now there won’t be any worries if a developer adds a new field type that implements IDisposable!

This code and more can be found in the dotNetTips.Utility assemblies on CodePlex.

Advertisements

One thought on “Make Disposing Objects Easier

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s