473,473 Members | 2,169 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

return inside of using block

Are these two equivalent? Is one better than the other? I tend to go with #1
but started wondering....

Thanks,

1:

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

return (int)cm.Parameters["@Count"].Value;
}

2:

int count;

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

count = (int)cm.Parameters["@Count"].Value;
}

return count;
May 31 '06 #1
8 3331
Yes. Why? Because using is actually implemented using try/finally

Regards,
Tiberiu Covaci.
"Andrew Robinson" <ne****@nospam.nospam> wrote in message
news:uh**************@TK2MSFTNGP03.phx.gbl...
Are these two equivalent? Is one better than the other? I tend to go with
#1 but started wondering....

Thanks,

1:

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

return (int)cm.Parameters["@Count"].Value;
}

2:

int count;

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

count = (int)cm.Parameters["@Count"].Value;
}

return count;

May 31 '06 #2
Andrew,

No, they are not equivalent to each other, technically. While they will
have the same results, it is different, as an exception thrown during return
statement will not cause the command and the connection to clean up. Of
course, in #2, they are already cleaned up because you left the scope of the
using statements anyways.

It also has the effect of keeping open the connection and the command
slightly longer.

As a side note, you don't need to explicitly call Close. It will be
called when Dispose is called on the connection.

Personally, I like the idea of returning while in the using statement
for this particular scenario. It seems more natural to me to access the
members that are dependent on that resource (parameters are from a stored
procedure executed on that connection) when the resource is alive, as
opposed to when it has been disposed already.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Andrew Robinson" <ne****@nospam.nospam> wrote in message
news:uh**************@TK2MSFTNGP03.phx.gbl...
Are these two equivalent? Is one better than the other? I tend to go with
#1 but started wondering....

Thanks,

1:

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

return (int)cm.Parameters["@Count"].Value;
}

2:

int count;

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

count = (int)cm.Parameters["@Count"].Value;
}

return count;

May 31 '06 #3
Nicholas,

I hadn't give this any thought in terms of exception handling. If my return
throws an exception, I tend to view this as an extraordinary event that I
currently don't handle and have no plans on handling. So if in that case
resources either get cleaned up or not, I don't think that is really all
that important.

Thanks,

--

Andrew Robinson
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:OQ**************@TK2MSFTNGP04.phx.gbl...
Andrew,

No, they are not equivalent to each other, technically. While they
will have the same results, it is different, as an exception thrown during
return statement will not cause the command and the connection to clean
up. Of course, in #2, they are already cleaned up because you left the
scope of the using statements anyways.

It also has the effect of keeping open the connection and the command
slightly longer.

As a side note, you don't need to explicitly call Close. It will be
called when Dispose is called on the connection.

Personally, I like the idea of returning while in the using statement
for this particular scenario. It seems more natural to me to access the
members that are dependent on that resource (parameters are from a stored
procedure executed on that connection) when the resource is alive, as
opposed to when it has been disposed already.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Andrew Robinson" <ne****@nospam.nospam> wrote in message
news:uh**************@TK2MSFTNGP03.phx.gbl...
Are these two equivalent? Is one better than the other? I tend to go with
#1 but started wondering....

Thanks,

1:

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

return (int)cm.Parameters["@Count"].Value;
}

2:

int count;

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add("@Count", SqlDbType.Int);
cm.Parameters["@Count"].Direction = ParameterDirection.Output;

cn.Open();
cm.ExecuteNonQuery();
cn.Close();

count = (int)cm.Parameters["@Count"].Value;
}

return count;


May 31 '06 #4

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:OQ**************@TK2MSFTNGP04.phx.gbl...
Andrew,

No, they are not equivalent to each other, technically. While they
will have the same results, it is different, as an exception thrown during
return statement will not cause the command and the connection to clean
up. Of course, in #2, they are already cleaned up because you left the
scope of the using statements anyways.

It also has the effect of keeping open the connection and the command
slightly longer.

As a side note, you don't need to explicitly call Close. It will be
called when Dispose is called on the connection.

Personally, I like the idea of returning while in the using statement
for this particular scenario. It seems more natural to me to access the
members that are dependent on that resource (parameters are from a stored
procedure executed on that connection) when the resource is alive, as
opposed to when it has been disposed already.

Hope this helps.


Nick, technically speaking, you are slightly off base here. The "using"
statement guarantees the object you are using will be disposed of prior to
exiting the block .. If there is an exception thrown, the using will still
"clean up" or dispose of the object being used :)

ms-help://MS.MSDNQTR.2003FEB.1033/csref/html/vclrfUsingStatement.htm

HTH,
Mythran

May 31 '06 #5
Mythran,

That's not what I am referring to. Yes, in both cases, the object is
disposed of properly. It's a matter of ^when^ the object is cleaned up.
The order of operations in #1 and #2 are different. Also, if an exception
is thrown, the order in which things happen is different.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mythran" <ki********@hotmail.comREMOVETRAIL> wrote in message
news:Oc**************@TK2MSFTNGP03.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:OQ**************@TK2MSFTNGP04.phx.gbl...
Andrew,

No, they are not equivalent to each other, technically. While they
will have the same results, it is different, as an exception thrown
during return statement will not cause the command and the connection to
clean up. Of course, in #2, they are already cleaned up because you left
the scope of the using statements anyways.

It also has the effect of keeping open the connection and the command
slightly longer.

As a side note, you don't need to explicitly call Close. It will be
called when Dispose is called on the connection.

Personally, I like the idea of returning while in the using statement
for this particular scenario. It seems more natural to me to access the
members that are dependent on that resource (parameters are from a stored
procedure executed on that connection) when the resource is alive, as
opposed to when it has been disposed already.

Hope this helps.


Nick, technically speaking, you are slightly off base here. The "using"
statement guarantees the object you are using will be disposed of prior to
exiting the block .. If there is an exception thrown, the using will still
"clean up" or dispose of the object being used :)

ms-help://MS.MSDNQTR.2003FEB.1033/csref/html/vclrfUsingStatement.htm

HTH,
Mythran

May 31 '06 #6
Comments in-line to refer what I'm talking about :)

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:eh**************@TK2MSFTNGP02.phx.gbl...
Mythran,

That's not what I am referring to. Yes, in both cases, the object is
disposed of properly. It's a matter of ^when^ the object is cleaned up.
The order of operations in #1 and #2 are different. Also, if an exception
is thrown, the order in which things happen is different.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mythran" <ki********@hotmail.comREMOVETRAIL> wrote in message
news:Oc**************@TK2MSFTNGP03.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:OQ**************@TK2MSFTNGP04.phx.gbl...
Andrew,

No, they are not equivalent to each other, technically. While they
will have the same results, it is different, as an exception thrown
during return statement will not cause the command and the connection to
clean up. Of course, in #2, they are already cleaned up because you
left the scope of the using statements anyways.

-----------
You said "While they will have the same results, it is different, as an
exception thrown during return statement will not cause the command and
connection to clean up.". Hmm, if an exception is thrown during the return
statement inside the using block, they will be cleaned up before the
exception is "bubbled up" the stack (in #1). In #2, the command and
connection are already cleaned up prior to the exception so no worries there
anyways.
It also has the effect of keeping open the connection and the command
slightly longer.

-----------
Unless you are doing something with the result besides returning it, it's
not keeping the command or connection open any longer in either one. If
anything, #2 is holding it open a little longer while it stores the result
into the var (insignificant timing though). In #1, it is returning the
value, which in this case, calls dispose immediately before exiting the
method, therefore cleaning up the command and connection.
As a side note, you don't need to explicitly call Close. It will be
called when Dispose is called on the connection.

-----------
Aye, when using the "using" statement, you don't have to Close ... Dispose
calls close... but here's the kicker! If you are using the "using"
statement on a SqlConnection object, you are effectively doing away with
connection pooling (someone PLEASE correct me if I'm wrong here). When you
call Dispose on a SqlConnection object, you are disposing of the object, not
just closing it. If you call Close, you are releasing it back into the
pool.
Personally, I like the idea of returning while in the using statement
for this particular scenario. It seems more natural to me to access the
members that are dependent on that resource (parameters are from a
stored procedure executed on that connection) when the resource is
alive, as opposed to when it has been disposed already.

Hope this helps.


-----------
Aye, I feel the same way about returning while in the using statement.

HTH :)

Mythran

May 31 '06 #7
It's not the connection object that is pooled, it's the connection. When
the Close or Dispose methods are called, the connection is released to
the pool.

Calling the Dispose method doesn't dispose of an object, it lets the
object dispose of the unmanaged resources that it uses.

Mythran wrote:
Aye, when using the "using" statement, you don't have to Close ...
Dispose calls close... but here's the kicker! If you are using the
"using" statement on a SqlConnection object, you are effectively doing
away with connection pooling (someone PLEASE correct me if I'm wrong
here). When you call Dispose on a SqlConnection object, you are
disposing of the object, not just closing it. If you call Close, you
are releasing it back into the pool.

May 31 '06 #8
Mythran,

See inline:
-----------
You said "While they will have the same results, it is different, as an
exception thrown during return statement will not cause the command and
connection to clean up.". Hmm, if an exception is thrown during the
return statement inside the using block, they will be cleaned up before
the exception is "bubbled up" the stack (in #1). In #2, the command and
connection are already cleaned up prior to the exception so no worries
there anyways.
Right, there are no worries, but there is a difference. Compile each
code sample, and check the resulting IL. They are different.
Unless you are doing something with the result besides returning it, it's
not keeping the command or connection open any longer in either one. If
anything, #2 is holding it open a little longer while it stores the result
into the var (insignificant timing though). In #1, it is returning the
value, which in this case, calls dispose immediately before exiting the
method, therefore cleaning up the command and connection.
Actually, it is keeping it open longer. When the return statement is in
the "using" block, the expression "(int)cm.Parameters["@Count"].Value" is
evaluated before it is placed on the stack to be returned. Then the scope
is exited, and the connection/command is closed.

In #2, the connection and command are closed, then the expression
"(int)cm.Parameters["@Count"].Value" is evaluated (executed). Again, same
result, but different ways of going about it. The connection/command are
disposed of either way, but there is a difference in how it is obtained.
As a side note, you don't need to explicitly call Close. It will be
called when Dispose is called on the connection.

-----------
Aye, when using the "using" statement, you don't have to Close ... Dispose
calls close... but here's the kicker! If you are using the "using"
statement on a SqlConnection object, you are effectively doing away with
connection pooling (someone PLEASE correct me if I'm wrong here). When
you call Dispose on a SqlConnection object, you are disposing of the
object, not just closing it. If you call Close, you are releasing it back
into the pool.
That is not true. For more information, see:

http://msdn2.microsoft.com/en-US/library/8xx3tyca.aspx

Basically, Close and Dispose do the same thing (there are slight
differences in the code, but they have the same effect).
Personally, I like the idea of returning while in the using
statement for this particular scenario. It seems more natural to me to
access the members that are dependent on that resource (parameters are
from a stored procedure executed on that connection) when the resource
is alive, as opposed to when it has been disposed already.

Hope this helps.


-----------
Aye, I feel the same way about returning while in the using statement.

HTH :)

Mythran

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
Jun 1 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: randomtalk | last post by:
hi, i have the following recursive function (simplified to demonstrate the problem): >>> def reTest(bool): .... result = .... if not bool: .... reTest(True) .... else: .... print...
14
by: dcassar | last post by:
I have had a lively discussion with some coworkers and decided to get some general feedback on an issue that I could find very little guidance on. Why is it considered bad practice to define a...
6
by: ste.paoletti | last post by:
hi, I have read that browsers support block element inside inline element but the css is not valid. Someone can tell me more about? What do you think? Thanks.
40
by: Mark P | last post by:
I'm implementing an algorithm and the computational flow is a somewhat deep. That is, fcn A makes many calls to fcn B which makes many calls to fcn C, and so on. The return value of the outermost...
21
by: Jim Langston | last post by:
I'm sure this has been asked a few times, but I'm still not sure. I want to create a function to simplify getting a reference to a CMap in a map. This is what I do now in code: ...
2
by: taras.di | last post by:
Hi everyone, I know that there's been a bit of discussion involving placing <div>s inside table cells, but I've read all of the posts and couldn't find anything that solved my problem. I've...
22
by: semedao | last post by:
Hi , I am using asyc sockets p2p connection between 2 clients. when I debug step by step the both sides , i'ts work ok. when I run it , in somepoint (same location in the code) when I want to...
13
by: alvin.yk | last post by:
Hi, Normally, a piece of code such as <a href="http://www.yahoo.com" onclick="alert('hello');return false;">link</a> will stop the browser from actually going to href's destination....
5
by: SuneR | last post by:
Hi, I am having problems figuring out how to make Firefox behave, and output the HTML I want it to output. The thing I want done is actually quite simple. I have a <labeltag, and inside it, I...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.