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:
{
private System.Data.Entity.DbContext _context;
{
Dispose(false);
}
{
Dispose(true);
GC.SuppressFinalize(this);
}
{
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:
{
[System.Runtime.CompilerServices.Extension()]
public static void DisposeFields(IDisposable obj)
{
var objs = obj.GetType().GetFields().Where(p => p.GetType()
}
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:
{
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.
Discover more from dotNetTips.com
Subscribe to get the latest posts sent to your email.

One thought on “Make Disposing Objects Easier”