Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using keyword- nested in single line

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.

like image 396
binball Avatar asked Mar 09 '10 12:03

binball


2 Answers

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 
}
like image 127
Marc Gravell Avatar answered Sep 23 '22 09:09

Marc Gravell


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.
like image 30
Tuukka Haapaniemi Avatar answered Sep 21 '22 09:09

Tuukka Haapaniemi