0

Possible Duplicate:
in a “using” block is a SqlConnection closed on return or exception?

Would this using close this _connection?

using(SqlConnection _connection = Class1.GetSqlConnection())  
{   //code inside the connection
}

//connection should be closed/ended?

I'm just wondering because GetSqlConnection() is a static function of Class1 and the whole connection might not be closed because it is calling outside class' static function instead of straight?

 using(SqlConnection _connection = new SqlConnection(_connectionString)
 {   //code inside the connection
 }
Community
  • 1
  • 1
iefpw
  • 6,816
  • 15
  • 55
  • 79

3 Answers3

1

The using statement does not care how the variable gets its value, - be it from a static function, a member function, a new operator, or any other way. As soon as the closing brace of the using is reached, the Dispose() method on the variable will be called, closing the connection if it's an IDbConnection instance, or doing whatever else the IDisposable is to do upon disposing.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Yes, by design.

A using block is used to handle disposing of, well, disposable objects when the block ends. To Dispose() an object means to release all of the resources for that object. For objects such as SqlConnection, this will close their connection.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
0

Yes it does.

Here is an alternative way to implement the GetSqlFunction method so that you have a more explicit behaviour:

public class Class1
{
    private static SqlConnection GetSqlConnection() { /* unchanged */ }

    public static void UseSqlConnection(Action<SqlConnection> action)
    {
        using (var connection = Class1.GetSqlConnection())
        {
            action(connection);
        }
    }
}

Then you call it like so:

Class1.UseSqlConnection(c =>
{
    /* use connection here */
});

You could then extend this method to use an existing connection or create a new one depending on the semantics you prefer.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172