Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling IDisposables within another IDisposable "using" statement

Tags:

c#

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 (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
        }
    }
}
like image 789
Tom S Avatar asked Dec 06 '25 20:12

Tom S


1 Answers

Strictly speaking, it would indeed be best to dispose all of them. However, you can avoid the indenting by nesting them directly:

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

Alternatively, specifically in the case of ADO.NET (which does, let's be fair, have a lot of disposable types), you might find it easier to use one of the libraries that hides away a lot of the plumbing - for example, with "dapper":

using(var conn = new SqlConnection(...))
{
    return conn.Query<Customer>(
        "select * from Customers where Region=@region",
        new { region }).ToList();
}
like image 52
Marc Gravell Avatar answered Dec 08 '25 20:12

Marc Gravell