Trying to better understand "use"

I read a couple of articles about using instructions to try to understand when it should be used. Most people seem to think that it should be used as much as possible, since it guarantees the removal of unused objects.

The problem is that all the examples always show something like this:

using (SqlCommand scmFetch = new SqlCommand())
{
    // code
}

It makes sense, but it's such a small piece of code. What to do when executing a query in a database? What are all the steps? Would it look something like this:

string sQuery = @"
    SELECT [ID], [Description]
    FROM [Zones]
    ORDER BY [Description] ";

DataTable dtZones = new DataTable("Zones");

using (SqlConnection scnFetchZones = new SqlConnection())
{
    scnFetchZones.ConnectionString = __sConnectionString;
    scnFetchZones.Open();

    using (SqlCommand scmdFetchZones = new SqlCommand())
    {
        scmdFetchZones.Connection = scnFetchZones;
        scmdFetchZones.CommandText = sQuery;

        using (SqlDataAdapter sdaFetch = new SqlDataAdapter())
        {
            sdaFetch.SelectCommand = scmdFetchZones;
            sdaFetch.Fill(dtZones);
        }
    }

    if (scnFetchZones.State == ConnectionState.Open)
        scnFetchZones.Close();
}

I want to know:
• Is it possible to have 4, 5, 10 nested with operators to provide all objects?
• At what point am I doing something wrong and should I review?
• If you need to change - , ?

, , ? , , SqlDataAdapter using, - , ?

Thanx.

+5
8

:

using(A a = new A())
using(B b = new B())
{
   a.SomeMethod(b);
}
+8

, IDisposable. , .

+2

- #.

, :

using(var someDisposableObject = new someDisposableObject())
{
    // Do Something
}

:

var someDisposableObject = new someDisposableObject();
try
{
  // Do Something
}
finally
{
   if (someDisposableObject != null)
   {
       ((IDisposable) someDisposableObject).Dispose();
   }
}

: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

+2

, . , IDisposable. , , , , .

, : , , , , , , . , . , .

, , , . , ( , ).

+1

• 4, 5, 10 , ?

: " ".

• - ?

: " ". , , .

        using (var con = new SqlConnection(connStr))
        using (var cmd = new SqlCommand(queryStry))
        using (var rs = cmd.ExecuteReader())
        {
            while (rs.Read())
            {
                //Code.
            }
        }
+1

3 (Connection, Command, Other) , , , , . , . , , " ".

, 10 !

0

, : ? / ? ? ? "".

using. # ++ RAII, : -)

0

, "" ClassFactories , DataReaders, .

private IDataReader CreateReader(string queryString,
    string connectionString)
{
    SqlConnection connection = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand(queryString, connection);
    connection.Open();
    return command.ExecuteReader(CommandBehavior.CloseConnection);
    // Don't close connection
}

( MSDN - MSDN - )

WCF ServiceReference - , "" . IMHO.

0

All Articles