C# Using keyword- nested in single line
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:
- A more detailed description in Christian Nagel's blog on the new using declaration
- The official documentation.
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.