I just started to use "using" to make sure resources are disposed regardless of what happens.
Below is an example of some code that I have written to retrieve some data. My question is:
Are all the "using" required or would it be enough to just have the first one?
SomeMethod()
{
using (SqlConnection cn = new SqlConnection("myConnection"))
{
cn.Open();
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "myQuery";
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.HasRows)
{
while (rdr.Read())
// do something
}
}
}
}
}
Using is nothing else than :
SomeClass o = null;
try
{
// managed resource that you use
o = new SomeClass();
// ... some other code here
}
finally
{
if(o != null)
o.Dispose();
}
There is nothing wrong with a fact that you use using
statement when it is possible (class implements IDisposable
interface). When you want to use some managed resource then use using :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With