Is there a problem with the second usage(Code snippet 2)? If so, what is the problem?
// ---Code snippet 1---
IDbConnection connection = new SqlConnection(connStr)
using(connection)
{
connection.Open(); // Open a connection in “using”
todo...
}
// ---Code snippet 2---
IDbConnection connection = new SqlConnection(connStr)
connection.Open(); // Open a connection outside “using”
using(connection)
{
todo...
}
CodePudding user response:
The using
statement is just built-in language support for correct handling of IDisposable
objects, using it you can make sure, that your disposable objects are disposed when they should be.
It basically translates to a try-finally pair, with a dispose call in the finally block. You can read more about the using statement here.
That said, you should put the using
keyword on the first statement you are creating the disposable object, so the correct version of your code would be:
using (var connection = new SqlConnection(connStr))
{
connection.Open(); // Open a connection in “using”
todo...
}
I don't think the placement of the using keyword makes any difference on what the connection object does or looks like.