Using Statement That Returns Values

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mcfly1204
    New Member
    • Jul 2007
    • 233

    #1

    Using Statement That Returns Values

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

    using (SqlConnection Conn = new SqlConnection(s trConn))
    {
    SqlCommand cmd = new SqlCommand("spW hatever", Conn);
    cmd.CommandType = CommandType.Sto redProcedure;
    cmd.Parameters. Add("@parm1", SqlDbType.VarCh ar, 128);
    cmd.Parameters["@parm2"].Value = strOne;

    Conn.Open();

    string strReturn = cmd.ExecuteScal ar().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.ExecuteScal ar().ToString() ;

    new Method(strRetur n);
    }
  • nateraaaa
    Recognized Expert Contributor
    • May 2007
    • 664

    #2
    New methods are not necessary you just need to declare your return variable above the using statements instead of within the using statement.

    Code:
    string returnVariable = string.Empty;
    
    using()
    {
    //do processing
    returnVariable = "something";
    }
    
    using()
    {
    parameter = returnVariable;
    }
    Nathan

    Comment

    • mcfly1204
      New Member
      • Jul 2007
      • 233

      #3
      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.

      Comment

      Working...