Give a hoot.. implement IDisposable (posted by Arturo)

One of the perils of managed code taking memory management out of developers’ hands is that we often become careless when working with large objects and resources. While the GC does its job quite well, there is still no substitute for good memory conservation practices.

One of my favorite little tricks for this is the using Statement. Not to be confused with the using Directive, the using Statement allows us to very clearly define a scope for an object, and clean it up immediately, regardless of how we exit that defined scope. (Either by reaching the end, or a transfer of control caused by an Exception.)

Ex:

using(MyClass obj = new MyClass())
{
//..ingenious and interesting code
}

All we have to do is make sure the class implements the IDisposable interface, which consists of a single method: Dispose(), and the above code will automatically invoke that method. In there we can null out all our references, clean up any large collections that our class may define, disconnect from any network resources, close any files, anything we shouldn’t keep around longer than absolutely necessary.

class MyClass : IDisposable
{
private ArrayList m_Items;

 

 public void AddItem(object item)
{
m_Items.Add(item);
}

 

 public void Dispose()
{
if(m_Items != null)
{
m_Items.Clear();
m_Items = null;
}
}
}

One of the most useful places for this is when managing SqlConnections. 

using(SqlConnection conn = new SqlConnection(connString))
{
//…ingenious Data Access
}

That little tidbit of code will take care of closing your connection, and disposing of the object, even if an unexpected error occurs in the middle of interacting with the target database… essentially for free.

You may be saying to yourself, “self…. If disposing on an unhandled exception is my concern, couldn’t I just use a try{} catch{} finally{}?” . Yes, you very well could. There’s lots of ways skin a cat as my colleague Aaron so eloquently examines, but why leave disposing of something as expensive as a SqlConnection as an afterthought in the finally{} clause that a developer might simply forget about. Not only that, consider the stylistic advantages that the using clause gives to your code. Now, a new developer on this codebase can very quickly examine the precise scope of these connections, and determine where to add their new stored procedure call.

Gifford Pinchot once said: “Conservation is the foresighted utilization, preservation and/or renewal […], for the greatest good of the greatest number for the longest time.” A good philosophy in life, and in software development.

-arturo