Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested using statements in C#

Tags:

c#

.net

file

using

I am working on a project. I have to compare the contents of two files and see if they match each other precisely.

Before a lot of error-checking and validation, my first draft is:

  DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory + "\\TestArea\\");   FileInfo[] files = di.GetFiles(filename + ".*");    FileInfo outputFile = files.Where(f => f.Extension == ".out").Single<FileInfo>();   FileInfo expectedFile = files.Where(f => f.Extension == ".exp").Single <FileInfo>();    using (StreamReader outFile = new StreamReader(outputFile.OpenRead()))   {     using (StreamReader expFile = new StreamReader(expectedFile.OpenRead()))     {       while (!(outFile.EndOfStream || expFile.EndOfStream))       {         if (outFile.ReadLine() != expFile.ReadLine())         {           return false;         }       }       return (outFile.EndOfStream && expFile.EndOfStream);     }   } 

It seems a little odd to have nested using statements.

Is there a better way to do this?

like image 782
SBurris Avatar asked Aug 25 '09 17:08

SBurris


People also ask

Can we use nested using in C#?

Nesting of a while loop is allowed, which means you can use while loop inside another while loop. However, it is not recommended to use nested while loop because it is difficult to maintain and debug. Example: C#

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

Does using statement Call dispose?

The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.


1 Answers

The preferred way to do this is to only put an opening brace { after the last using statement, like this:

using (StreamReader outFile = new StreamReader(outputFile.OpenRead())) using (StreamReader expFile = new StreamReader(expectedFile.OpenRead()))  {     ///... } 
like image 59
SLaks Avatar answered Sep 19 '22 22:09

SLaks