Reputation: 2345
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.
Upvotes: 8
Views: 8386
Reputation: 1264
With C# 8 you can get rid of even the single nesting level:
private static void NewMultipleUsingDeclarations()
{
using var xmlStream = client.OpenRead(xmlUrl);
using var xmlReader = new XmlTextReader(xmlStream);
// use xmlReader
}
Internally the compiler creates an equivalent try catch as with the indented version and disposes of both the stream and the reader at the end of the scope of the using variables, in this case, at the end of the method.
See more:
Upvotes: 12
Reputation: 532445
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 ))
{
...
}
Upvotes: 2
Reputation: 62093
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.
Upvotes: 2
Reputation: 1062512
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
}
Upvotes: 23