Search code examples
c#sqlconnectionusing-statement

using statements


Today I noticed a snippet of code that looks like the one below:

public class Test
{
    SqlConnection connection1 = 
      new SqlConnection(ConfigurationManager.ConnectionStrings["c1"].ToString());
    SqlConnection connection2 = 
      new SqlConnection(ConfigurationManager.ConnectionStrings["c2"].ToString());

    public void Method1()
    {
        using (connection1)
        {
            connection1.Open();
            using (SqlCommand newSqlCommand = new SqlCommand("text",connection2))
            {
            // do something       
            }         
        }
    }

    public void Method2()
    {
        using (connection1)
        {
            // do something                
        }
    }
}

I am just wondering why would anyone want to open the connection when creating the class and not when calling the corresponding methods inside the class?

EDIT: I should have probably posted the whole code instead. So I do see where they are opening connection1, but then they are instantiating a sqlcommand with a different sql connection (connection2) which has not been opened anywhere. What am I missing here?

Thanks,


Solution

  • This line only initializes a connection object, which can later be used to open a connection to a database server.

    SqlConnection connection1 = 
    new SqlConnection(ConfigurationManager.ConnectionStrings["c1"].ToString());
    

    What I know is that using disposes of an object (and in the case of Connection objects they are automatically closed) after its scope so I wouldn't recommend such usage because it might be problematic with other object types (other than Connection) that can't be used after having their dispose called.