Home > OS >  why we use nested using statement in c#?
why we use nested using statement in c#?

Time:12-12

using (StreamReader outFile = new StreamReader(outputFile.OpenRead())) 
{    
   StreamReader resFile = new StreamReader(resultFile.OpenRead())    
   {       //Some Codes    }
}

Why does the above resFile object not close automatically?

I wrote the resFile object inside the using statement also. Please explain the using statement.

CodePudding user response:

You didn't use nested using. There's only one using statement.

An example of nested using:

using (...)
{
     using (...)
     {
         ...
     }
}

The reason why you may want to use nested using is that you have more than one declaration that need to be disposed.

CodePudding user response:

Find the official explanation for the using statement here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

In your example you are not having a nested using statement as Mark said correctly in his answer. (Though you should have a second using for the resFile Streamreader.

They have to be nested, if you want to use both stream readers in the "// Some Codes" part, as the instances for outFile and resFile are only available inside the curly brackets.

Starting from C#8 there is a new possibility for usings that "avoids" the nesting. See: https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/proposals/csharp-8.0/using

CodePudding user response:

using is syntactic sugar and basically compiles to the following:

Original code:

using (var a = b)
{    
  c();
  d();
}

Desugared code:

{
  var a;
  try {
    a = b;
    c();
    d();
  } finally {
    if (a != null) {
      ((IDisposable)a).Dispose();
    }
  }
}
  • Related