Question

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.

Was it helpful?

Solution

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 
}

OTHER TIPS

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.

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 ))
{
   ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top