Home
Do you use "using" statement instead of use explicitly "dispose"?
  v1.0 Posted at 27/04/2018 6:59 AM by Tiago Araujo
Don't explicitly use "dispose" to close objects and dispose of them, the "using" statement will do all of them for you. It is another awesome tool that helps reduce coding effort and possible issues.

SqlConnection conn = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection(ConnectionString);
cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
...
}
finally
{
if(cmd!=null)
{cmd.Dispose();}
if(conn!=null)
{conn.Dispose();}
}

Figure: Bad example of dispose of resources


FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs); 

Figure: Bad example of dispose of resources


try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (cmd = new SqlCommand(sql, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
catch(SqlException ex)
{
...
}

Figure: Good example of dispose of resources

using(FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
...
}
}

Figure: Good example of dispose of resources  ​


Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.