Question

I am working on application in which i need to access database. Use of using statement is good because "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens. So i am little bit confused where to use "using" and where to not.

public int route(Route r)
{
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using(SqlCommand com = new SqlCommand("",con))
            {
                using (SqlDataReader sdr = com.ExecuteReader())
                {
                }
            }
        }
    }
    catch (Exception e)
    {
    }
}
Was it helpful?

Solution

Any time an object you create implements IDisposable, disposing of it (with or without the using syntactic sugar) is a good idea.

The benefit of the using block syntactic sugar (over manual .Dispose() calls) is that Dispose() will still be called even if there is an exception and flow leaves the using block.

Also, note that you can stack up the usings, without nested indentation:

using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
   ...

As an aside, a further benefit of using is that if the IDisposable variable is declared within the using, it that the variable is readonly and cannot be reassigned within the block, e.g.:

using (SqlDataReader sdr = com.ExecuteReader())
{
   sdr = new SqlDataReader() // Error

OTHER TIPS

You can simplify it like this:

using (SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader())
{
     ...
}

Using statements are translated to try/finally blocks.Therefore your object will be Disposed even if there is an exception thrown.So if you have a Disposable object and you want to ensure that it will be Disposed after it's used, you can use using statements.Remember it's kind a syntactic sugar for this:

SqlCommand cmd;
try
{
    cmd = new SqlCommand();
    ...
}
finally
{
   ((IDisposable)cmd).Dispose();
}

This looks okay as far as using blocks are concerned.

However, you should NOT use a try/catch block here, unless you intend on actually doing something with the exception. Otherwise you are just hiding possible errors away, which is dead wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top