Alex Rivera | Logout

C# - closing Sql objects best practice

Asked 2008-11-29T21:02:14.873
11

If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function

For example:

void DoSqlStuff()
{
    SqlConnection sqlConn = new SqlConnection(...);
    SqlCommand cmd = new SqlCommand(...);
    SqlDataReader sqlData= null;

    sqlConn,Open();
    sqlData = cmd.ExecutReader();


    while(sqlData.Read())
    {
         ...
    }
}

Is it optional, recommended or mandatory to close SqlConn and SqlData?

Thanks.

Edit
Report

2 Answers

2

You should close everything before returning from the function. Open datareaders mean open cursors on the database, resulting in increased memory usage. Same goes for database connections.

Unused objects are not immediately freed in C#, but only when garbage collection is performed, which is not deterministic.

answered 2008-11-29T21:29:27.877
0

Any class handling SQL stuff like Connections should implement the IDisposable interface as stated by Microsoft .NET coding guidelines.

Thus, you should probably close and dispose your connection in your Dispose method.

answered 2008-11-29T21:10:51.127

Your Answer