views:

199

answers:

3

Hi,

Usually I was doing something like that (just a example):

using (Stream xmlStream = client.OpenRead(xmlUrl))
{
    using (XmlTextReader xmlReader = new XmlTextReader(xmlStream))
    {
    }
}

Isn't better to do just:

using (XmlTextReader xmlReader = new XmlTextReader(client.OpenRead(xmlUrl)))
{
}

But I'm not sure if in this short syntax all resources will be disposed (Stream) or only XmlTextReader?

Thanks in advance for your answer.

+18  A: 

No; that won't guarantee that the Stream is disposed if the XmlTextReader constructor throws an exception. But you can do:

using (Stream xmlStream = client.OpenRead(xmlUrl))
using (XmlTextReader xmlReader = new XmlTextReader(xmlStream))
{
    // use xmlReader 
}
Marc Gravell
The first sentence is great (+1 for that) but the remainder, isn't this (and TomTom) just syntactic sugar? It's actually identical to the original code isn't it?
Lazarus
@Lazarus - it does the same thing, but (importantly) it stops the nesting from pushing the code off the right hand side of the screen ;-p In all seriousness, we're encapsulating a single unit here, so a single level of *visual* nesting seems desirable.
Marc Gravell
I didn't realise that this would stop the indent, it operates differently to an if statement which indents even if you omit the brackets for single line blocks. I learnt something... it's a good day ;)
Lazarus
+2  A: 

What about (I use this now):

using (Stream xmlStream = client.OpenRead(xmlUrl))
using (XmlTextReader xmlReader = new XmlTextReader(xmlStream))
{
...
}

The second using is the referenced using from the first - no need to have brackets.

TomTom
+2  A: 

The reference documentation indicates that the object to be disposed must be declared in the using statement. Since there is no declaration for the stream, the Dispose method will not be called.

In your case you could skip the stream entirely, though, and use the constructor for the TextReader that takes a url parameter. The underlying stream will be closed when the reader is disposed.

using (var xmlReader = new XmlTextReader( xmlUrl ))
{
   ...
}
tvanfosson