Got more questions? Find advice on: ASP | XML | Regular Expressions | Windows
in Search
Welcome to SqlAdvice Sign in | Join | Help

The Penton-izer

I have moved to http://pentonizer.com so join me there!!!

More on Interfaces for System.Data

Aaron blogged about interfaces and asked about people usage.  I have been using them more and more in code.  Here are some examples of closing and disposing of System.Data (and Microsoft.Data) resources using interfaces:

static void DisposeIDbDataAdapter(ref IDbDataAdapter da)
{
 if(da != null)
 {
   if(da is IDisposable) ((IDisposable)da).Dispose();
   da = null;
 }
}
static void DisposeIDataReader(ref IDataReader dr)
{
 if(dr != null)
 {
   dr.Dispose();
   dr = null;
 }
}
static void DisposeIDbCommand(ref IDbCommand cmd)
{
 if(cmd != null)
 {
   cmd.Dispose();
   cmd = null;
 }
}

static void DisposeIDbConnection(ref IDbConnection conn)
{
 if(conn != null)
 {
   if(conn.State != ConnectionState.Closed) conn.Close();

   conn.Dispose();

   conn = null;
 } 
}
Ok...some questions I am sure will come of this.  First off, why do this?  Well, these methods can be used for any of the major providers (SqlClient, Odbc, OleDb, OracleClient and others).  Much less code to write and maintain.  Why the ref keyword?  Well, if you have been keeping up with Paul Wilson (here, here, and here) you'd see that his tests show there is some benefit to setting variables to null (Nothing in VB.Net).  I use the ref keyword to allow me to operate on the original variable (not only the original object).  Why the check on IDbDataAdapter?  Well, System.Data.IDbDataAdapter does not implement IDisposable, but the major providers do implement IDisposable (it is in its inheritance chain).  Also, why do I call IDbConnection.Close() AND IDbConnection.Dispose()?  If you check System.Data.SqlClient.SqlConnection in Anakrino, you'l see that Dispose(bool disposing) does indeed call Close().  Note the signature diferences?  We can only call the publically available Dispose() method, not the protected Dispose(bool disposing) method.  We have to depend on the framework to manage that.  So, even if doing all of this doesn't buy me much, what it does buy me is refactored and self-documented code.  Of course, don't forget the C# comments that belong on these functions. :-)

One other thing to add: The using keyword.  Why not always use that?  You can use it when your coding methodology calls for it.  In fact, use it as much as you can.  Where it makes sense.

Are there better ways of doing this?  I am sure that there are.  It would be short order to deal with that with this framework.  If anything refactoring and self-documentation are worth it to me.
Sponsor
Published Tuesday, March 16, 2004 2:09 PM by dpenton

Comments

 

dpenton said:

Nice, I'm going to have to add these to my utility or Base DAL class...
March 16, 2004 11:37 PM
Anonymous comments are disabled