USING block in C#

RadhaKrishnaKiJaya used Ask the Experts™
Hello Experts,
In the code below,  what happens to the value of Output parameter parm[1] and variable returnId inside and outside the USING block in C#?  Please try to help.

 { using (SqlConnection connection = SqlHelper.GetConnection())
               parm = new SqlParameter[2];
               parm[0] = SqlHelper.CreatePerameter("@Id", SqlDbType.VarChar, sId, ParameterDirection.Input, 50, false);
               parm[1] = SqlHelper.CreatePerameter("@Error_Msg", SqlDbType.VarChar, 0, ParameterDirection.Output, 500, false);

               returnId = SqlHelper.ExecuteNonQuery(SqlHelper.GetConnection(), CommandType.StoredProcedure, "usp_deleteRejectedItems", parm);
               strErrorMessage = parm[1].Value.ToString();
               intReturnId = returnId;

    strErrorMessage = parm[1].Value.ToString();
    intReturnId = returnId;   

Open in new window

Thank you in advance for you time and help.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

OK. A couple of things of note. You seem to have your curly brackets in the wrong place. Normally, you go like this:

using (...) {

The using statement is effectively a shortcut to instantiate and dispose of an object. In your case, you're instantiating connection and then disposing of it at the end of the using block, but you're never actually using it.

Now as for what happens to your variables ... nothing. You must be declaring your variables (parm, intReturnId, returnId) outside of the using block, so they'll still be available outside of your using block.


Hello Chris,
Thank you.  If I use Result Set or Sql Reader instead, is it going to retain the data even after the connection is closed?  Asking this because I got the error message with SqlReader when tried to use the data after connection was closed.  

Error Message: ExecuteReader requires an open and available Connection. The connection's current state is closed.

Thank you!
Developer User Interface
Yeah. DataReader is an connected architecture. Dataset is a disconnected architecture.

Datareader will require an open connection
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Normally, you go like this:
Ewwww...  this isn't Java   =P

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial