Craig Johnston
Craig Johnston

Reputation: 7607

Will a using block close a database connection?

using (DbConnection conn = new DbConnection())
{
    // do stuff with database
}

Will the using block call conn.Close()?

Upvotes: 51

Views: 32743

Answers (4)

Roman
Roman

Reputation: 10403

A using block will ensure the destruction of DbConnection object by calling the Dispose() method. The Dispose() method will in turn call the Close() method and has to wait for it to finish closing the connection to the database.

Upvotes: 8

vlad259
vlad259

Reputation: 1236

Yes - http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx

edit: from Microsoft: "The connection is automatically closed at the end of the using block."

Upvotes: 8

BoltClock
BoltClock

Reputation: 724552

Yes, it will; the implementation of DbConnection.Dispose() calls Close() (and so do its derived implementations).

Upvotes: 69

Davide Piras
Davide Piras

Reputation: 44605

surely yes because it will dispose the connection and before disposing the inner logic of the connection calls the close.

Upvotes: 6

Related Questions