Question: I have following statement using `using`:

```
using (var reader = data.CreateCommand(sql).ExecuteDataReader())

```

in this case `data` is some object which internally holds `SqlConnection`. `CreateCommand(sql)` function returns `SqlCommand` and `ExecuteDataReader` returns `SqlDataReader`. Since `SqlCommand` and `SqlDataReader` are both `IDisposable`, will they both be disposed by this use of `using` statement?

For now I have done it like this:

```
using (var cmd = data.CreateCommand(sql))
using (var reader = cmd.ExecuteDataReader())

```

But I would like to know if it's possible to combine them as stated above?

Answer: 
*"if it's possible to combine them"* - two `using` are totally fine, because both needs to be disposed.

You can combine them by extracting into method:

```
void RunWithReader(string sql, Action<SQLDataReader> action)
{
    using (var cmd = data.CreateCommand(sql))
    using (var reader = cmd.ExecuteDataReader())
        action(reader);
}

```

Then you can use lambda

```
RunWithReader("whatever command", reader =>
{
    ... // while(reader.Read() { ... } - this could also be extracted
});

```
The way you have presented your code the inner `IDisposable` (`IDbCommand`) is not disposed.

You have two choices:

You can put it all in one `using` like this:

```
using (IDisposable cmd = data.CreateCommand(), reader = ((IDbCommand)cmd).ExecuteReader())
{
    // code here
}

```

But that is rather cumbersome. The other option is nested `using` statements:

```
using (var cmd = data.CreateCommand())
{
    using (var reader = cmd.ExecuteReader())
    {
        // code here
    }
}

```

Other than that you can get a bit complicated and write an extension method to help (sort of) clean it up for you.

```
public static class Ex
{
    public static void Using<T, R>(this T obj, Func<T, R> create, Action<T, R> use) where R : IDisposable
    {
        using (var d = create(obj))
        {
            use(obj, d);
        }
    }
}

```

Then you can do this:

```
data.Using(d => d.CreateCommand(), (d, c) => c.Using(c2 => c2.ExecuteReader(), (c3, r) =>
{
    // code here
}));

```

But perhaps that's not much of an improvement.