Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using keyword takes less space?

Tags:

c#

wpf

Is it true that if i use the following, it will take less resources and the cleanup will be faster?

 using (TextReader readLogs = File.OpenText("C:\\FlashAuto\\Temp\\log.txt"))
 {
      //my stuff
 }

as compared to:

 TextReader readLogs = new StreamReader("C:\\FlashAuto\\Temp\\log.txt");
 //my stuff
readLogs.Close();
readLogs.Dispose();
like image 240
Rohan Avatar asked Nov 08 '11 10:11

Rohan


1 Answers

The difference between those examples isn't performance, but exception safety. using creates a try...finally block in the background.

A using statement of the form:

using (ResourceType resource = expression) embedded-statement 

corresponds to the expansion:

{ 
   ResourceType resource = expression; 
   try {     
     embedded-statement 
   } 
   finally { 
     // Dispose of resource 
   } 
}

For reference type the disposing happens via:

finally {  
  if (resource != null) ((System.IDisposable)resource).Dispose(); 
}

From ECMA-344 C# Language Specification 4th Edition


You also don't need to call both Close and Dispose. Those functions are equivalent.

like image 154
CodesInChaos Avatar answered Sep 25 '22 15:09

CodesInChaos