Dispose your resources

Jan 27, 2012 at 6:11 PM

Instead:

public static DataTable GetDataTable(string sql, string connString)
        {
            SqlConnection dbCon = null;
            DataTable newTable = new DataTable();
            try
            {
                dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings[connString].ConnectionString);
                SqlCommand command = new SqlCommand(sql, dbCon);
                command.CommandTimeout = KTimeout;
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                dbCon.Open();
                adapter.Fill(newTable);
            }
            finally
            {
                if (dbCon != null && dbCon.State != ConnectionState.Closed)
                {
                    dbCon.Close();
                }
            }

            return newTable;
        }

I would write:

public static DataTable GetDataTable(string sql, string connString)
        {
            DataTable newTable = new DataTable();
            using (var dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings[connString].ConnectionString))
            {
                using (SqlCommand command = new SqlCommand(sql, dbCon))
                {
                    command.CommandTimeout = KTimeout;
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    dbCon.Open();
                    adapter.Fill(newTable);
                }
            }
            return newTable;
        }
Same functionality but resource safe:

SqlConnection and SqlCommand both implement 

IDisposable which is best handled with the 'using' statement

:-)