Possible Duplicate:
Will a using block close a database connection?
Is db.Close()
unnecessary in the following?
using (DbConnection db = GetDbConnection())
{
// do data-access stuff
// ...
db.Close();
}
Possible Duplicate:
Will a using block close a database connection?
Is db.Close()
unnecessary in the following?
using (DbConnection db = GetDbConnection())
{
// do data-access stuff
// ...
db.Close();
}
No, there is no need to close a DbConnection if a using clause is used?
and
Yes it is unnecessary in here because when scope of
using
ends, connection will dispose meaning closing and releasing all memory.Since
DBConnection
implementsIDisposable
interface, close function is there in theDispose
method ofDBConnection
.But if some lines are after close line then it is useful
But here it is useful
In that case you can do
For what I know, when
Dispose()
method is called,Close()
is automatically performed.So
db.Close();
is not necessary here.Just to be sure i have checked the code :)
This is the implementation of SqlConnection which is inheriting from DbConnection. As you can see there is this.Close() method :)
At the closing brace the
Dispose()
is called.I think in the
DbConnection
theDispose
method will also check if the connection is closed. So no, it probably isn't necessary, but I personally think it is good practice and improves readability and it doesn't affect performance because theClose
will be called one way or another.Extracted code from the dispose implementation of the
SqlConnection
(Derived ofDbConnection
) class:The
using
keyword uses theIDisposable
interface. The method above is the method implementation. It will close the connection.