Link to home
Start Free TrialLog in
Avatar of RadhaKrishnaKiJaya
RadhaKrishnaKiJaya

asked on

USING block in C#

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.
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

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.
Avatar of RadhaKrishnaKiJaya
RadhaKrishnaKiJaya

ASKER

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!
ASKER CERTIFIED SOLUTION
Avatar of Obadiah Christopher
Obadiah Christopher
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Chris
Normally, you go like this:
Ewwww...  this isn't Java   =P