By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,201 Members | 1,617 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,201 IT Pros & Developers. It's quick & easy.

using statement

P: n/a
I have a using statement something like the following

try
{
using(SqlConnection cnn = ...)
{
}
catch(Exception e1)
{
}

What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?
Thanks,
Sep 17 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
CSharper <cs******@gmx.comwrote:
try
{
using(SqlConnection cnn = ...)
{
}
catch(Exception e1)
{
}

What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?
Yes.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 17 '08 #2

P: n/a
CSharper brought next idea :
I have a using statement something like the following

try
{
using(SqlConnection cnn = ...)
{
}
catch(Exception e1)
{
}

What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?
Thanks,
Yes, the using statement is compiled similarly to

SqlConnection cnn = null;
try
{
cnn = ...;
// the "using block"
}
finally
{
if (cnn != null)
cnn.Dispose(); // which will close the connection
}

this does not "catch" any exceptions, so your own "catch" block can
handle them (but the connection is closed before your "catch" block is
activated).

Hans Kesting
Sep 17 '08 #3

P: n/a
On Sep 17, 10:34*am, Hans Kesting <news.han...@spamgourmet.comwrote:
CSharper brought next idea :
I have a using statement something like the following
try
{
* *using(SqlConnection cnn = ...)
* *{
* *}
catch(Exception e1)
{
}
What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?
Thanks,

Yes, the using statement is compiled similarly to

*SqlConnection cnn = null;
*try
*{
* *cnn = ...;
* *// the "using block"
* }
* finally
* {
* * if (cnn != null)
* * * cnn.Dispose(); // which will close the connection
* }

this does not "catch" any exceptions, so your own "catch" block can
handle them (but the connection is closed before your "catch" block is
activated).

Hans Kesting
Thanks both.
Sep 17 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.