The MSDN example you are talking to is specifically talking to the scenario where the inner object takes posession of the outer object; for example, a StreamWriter
can assume responsibility for a Stream
. In that scenario, disposing the inner object also causes the outer object to be disposed - but this is not true in the general case.
In particular, a command does not assume responsibility for disposing a connection. Interestingly, a data-reader can assume responsibility, but only via an optional flag.
Many such objects offer flags to let the caller determine whether the inner object should assume responsibility for disposing the outer object. For example, StreamWriter
also now offers a constructor-overload with a bool leaveOpen
parameter. If you pass this as true
, the StreamWriter
does not cascade the Dispose()
.
This is all implementation details of the inner object, when it is specifically written to do this. It is not a default behaviour of the using
pattern.
Side note: I would say MSDN is simply wrong here. The correct implementation is the first sample with two using
. The second example is non-intuitive, and prone to incorrect implementation. Don't use it. If necessary, use leaveOpen
to make is explicit, but frankly it usually works fine without this, if you are about to dispose it anyway.