-1

Do I really need to use comm.Dispose() and conn.Dispose() or directly used the using?

using (OdbcConnection conn = new OdbcConnection())
{
    conn.Open();
    OdbcCommand comm = new OdbcCommand(sql, conn);
    OdbcDataReader dr = comm.ExecuteReader();

    while (dr.Read())
    {
      //codes here...
    }

    conn.Close();
    dr.Close();
    comm.Dispose();
    conn.Dispose();
}

If that is the case, I'm thinking to do this.

Snippet:

using (OdbcConnection conn = new OdbcConnection())
{
    conn.Open();
    using(OdbcCommand comm = new OdbcCommand(sql, conn))
    {
        using(OdbcDataReader dr = comm.ExecuteReader())
        {
            while (dr.Read())
            {
                //codes here...
            }
        }
        dr.Close();

    }
    conn.Close();
}

Would this be more appropriate?

2 Answers2

1

Yes, you can just use using - it calls Dispose for you.

You can also omit the Close, because Dispose will call that for you.

using (OdbcConnection conn = new OdbcConnection())
{
    conn.Open();
    using(OdbcCommand comm = new OdbcCommand(sql, conn))        
    using(OdbcDataReader dr = comm.ExecuteReader())
    {
        while (dr.Read())
        {
            //codes here...
        }
    }            
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
1

The second example is appropriate (except for dr not being in scope when Close is called on it - also Dispose often calls Close for these types of things) as

using(IDisposable foo = ...)
{
    //Do stuff using foo
}

is equivalent to

IDisposable foo = ...;

try
{
    //Do stuff using foo
}
finally
{
    foo.Dispose();
}
mlorbetske
  • 5,529
  • 2
  • 28
  • 40