lakki
lakki

Reputation: 125

How to use Using statement for multiple instances?

I want to use using for SqlConnection and SqlCommand objects to dispose those. How can I use in this scenario?

for example:

using (sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL")))
{
}

But here I am using connection based on the if condition.

SqlConnection _sqlConnection;
SqlCommand sqlCmd;
DBPersister per = (DBPersister)invoice;
if (per == null)
{
    _sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"));
    sqlCmd = new SqlCommand("usp_UpdateDocumentStatusInImages", _sqlConnection);
}
else
{
    _sqlConnection = per.GetConnection();
    sqlCmd = per.GenerateCommand("usp_UpdateDocumentStatusInImages", _sqlConnection, per);
}

sqlCmd.CommandType = CommandType.StoredProcedure;
//mycode

try
{
    if (_sqlConnection.State == ConnectionState.Closed)
        _sqlConnection.Open();
    sqlCmd.ExecuteNonQuery();
}
catch
{
    throw;
}
finally
{
    if (per == null)
        invoice._sqlConnection.Close();
}

Upvotes: 1

Views: 805

Answers (2)

hcb
hcb

Reputation: 8357

You can nest them, like this:

using (var _sqlConnection = new SqlConnection(...))
{
    using (var sqlCmd = new SqlCommand(...))
    {
        //code
    }
}

Upvotes: 4

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239734

Use the conditional operator to determine what to assign to each variable:

using(SqlConnection _sqlConnection = per==null?
      new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"))
      : per.GetConnection())
using(SqlCommand sqlCmd = per==null?
      new SqlCommand("usp_UpdateDocumentStatusInImages", _sqlConnection);
      : per.GenerateCommand("usp_UpdateDocumentStatusInImages", 
       _sqlConnection, per))
{
  //Code here using command and connection
}

Although I must say, per.GenerateCommand(..., per) looks like an odd function (it's an instance method that also must be passed an instance of the same class - must it always be the same instance?)

Upvotes: 1

Related Questions