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.
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
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With