RAM,
When you have the using statement, the Dispose method on the IDisposable
implementation is called when the scope of the using statement is exited.
With the SqlConnection, calling Dispose is the same as calling Close, so
you don't have to explicitly call it. You can do this:
using (SqlConnection connection = new SqlConnection(C onnectionString ))
{
connection.Open ();
// Other stuff.
}
What this really compiles to is this:
SqlConnection connection = new SqlConnection(C onnectionString );
try
{
connection.Open ();
// Other stuff.
}
finally
{
if (connection != null)
{
// Call Dispose.
((IDisposable) connection).Dis pose();
}
}
So, if you have the need for exception handling, then you can use the
above construct and just insert the catch statements appropriately.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard. caspershouse.co m
"R.A.M." <r_********@poc zta.onet.pl> wrote in message
news:16******** *************** *********@4ax.c om...
Hello,
I have started larning C# and I have a question concerning "using
(...)" keyword.
For example:
using (SqlConnection connection = new SqlConnection(C onnectionString ))
{
connection.Open ();
...
connection.Clos e();
}
I can write it also this way:
SqlConnection connection;
try
{
connection = new SqlConnection(C onnectionString ));
connection.Open ();
...
connection.Clos e();
}
catch (...)
{
...
}
finally
{
...
}
But it won't dispose 'connection'.
Which solution is better? What are adventages and disadventages?
Thank you very much
/RAM/