Quantcast
Viewing latest article 7
Browse Latest Browse All 10

Nested Using Statements: A Belt and Suspenders kind of thing

A friend sent me the following question last week:

WIth the following code:

using(StringReader sr = new StringReader(someXmlString))
{
using (XmlReader reader = XmlReader.Create(sr))
{
// Do Something.
}
}


Is the second using statement really needed here as the underlying StringReader should be disposed of at the end of it’s using?

The answer is that the second using is redundant, but it has minimal cost, and it is guaranteed to work. One of the rules of IDisposable is that clients can call Dispose() multiple times and the effect must be the same as if it was called exactly once. (See Item 17 in Effective C#, 2nd edition for more details). The above code snippet will dispose twice, which is fine.

If I’m faced with a choice where my error is possibly disposing of a resource twice, versus some chance that a resource doesn’t get disposed at all, I’ll always choose the former. I’d leave this code exactly as it is written above.


Viewing latest article 7
Browse Latest Browse All 10

Trending Articles