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

Using Statement That Returns Values

P: 233
What is the best practice for returning values from within a using statement? For instance:

using (SqlConnection Conn = new SqlConnection(strConn))
SqlCommand cmd = new SqlCommand("spWhatever", Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@parm1", SqlDbType.VarChar, 128);
cmd.Parameters["@parm2"].Value = strOne;


string strReturn = cmd.ExecuteScalar().ToString();


And then I would like to pass strReturn to another using statement to be a value for another query. Do I need to make each using statement into a method and then call that method? Such as:

string strReturn = cmd.ExecuteScalar().ToString();

new Method(strReturn);
Nov 5 '08 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 663
New methods are not necessary you just need to declare your return variable above the using statements instead of within the using statement.

Expand|Select|Wrap|Line Numbers
  1. string returnVariable = string.Empty;
  3. using()
  4. {
  5. //do processing
  6. returnVariable = "something";
  7. }
  9. using()
  10. {
  11. parameter = returnVariable;
  12. }
Nov 5 '08 #2

P: 233
I suppose this is a case of trying before asking. I was thinking that if the variable was declared the value within the using statement, that the value would not be accessible elsewhere.
Nov 5 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.