HANDLING IDISPOSABLES WITHIN ANOTHER IDISPOSABLE “USING” STATEMENT

Babe Zaharias

Total Post:19

Points:133
Posted by  Babe Zaharias
C# 
C#
 1269  View(s)
Ratings:
Rate this:

I'm still relatively new to C# and have only within the past several days been exposed to "IDisposables". I can grasp the concept of the using block to take care of objects which must be disposed of without needing to manually remember to call the .Dispose() method - convenient!

Let's say though that I start with a new SqlConnection which I handle within a using statement. Within that block of code I create some additional IDisposables, for example a SqlDataAdapter. Does that adapter need it's own using statement?

For example, if I have code...

using (SqlConnection myConnection = new SqlConnection())

{
    SqlCommand myCommand = new SqlCommand();
    SqlDataAdapter myAdapter = new SqlDataAdapter();
    // Do things
}

... will myCommand and myAdapter be disposed of when myConnection is disposed of (since they are within the scope of that code block)? Or do I need multiple using statements, maybe something like:

using (SqlConnection myConnection = new SqlConnection())

{
    using (SqlCommand myCommand = new SqlCommand())
    {
        using (SqlDataAdapter myAdapter = new SqlDataAdapter())
        {
            // Do things
        }
    }
}

  1. Kate Smith

    Post:24

    Points:168
    Re: Handling IDisposables within another IDisposable “using” statement

    Hello Babe!

    Using is just syntatic sugar for



         var connection = new Connection();
    
            try
            {
                connection.DoSomething();
            }
            finally
            {
                // Check for a null resource.
                if (connection != null)
                {
                    ((IDisposable)connection).Dispose();
                }
            }


    So yes, you need nested using statements to be sure to dispose all of these

      Modified On Mar-31-2018 04:15:50 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!