Search code examples
c#usingusing-statement

why we use nested using statement in c#?


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.


Solution

  • 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.