Click here to Skip to main content
15,913,941 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my app i am using streamreader, streamwriter, and so on. I would like to use using statement, because there is no need for .Close(), .Dispose(),... is that right? Using makes it for you? And that releases the memory?
What is the rule where and how to use using?

And one more thing: Let say that i have a code for streamreader and i forgot to use .Close(), where in Visual Studio can i see (while debuging) that i forgot it and that it uses memory,...
Posted

 
Share this answer
 
Comments
Andreas Gieriet 26-Mar-13 18:32pm    
My 5!
Cheers
Andi
Thomas Daniels 27-Mar-13 3:21am    
Thank you!
"there is no need for .Close(),"

The using statement will call Dispose, and Dispose will call Close (in most classes that have a Close), but I still call Close as a matter of discipline; there's no reason not to.
 
Share this answer
 
Comments
Andreas Gieriet 26-Mar-13 18:34pm    
My 5!
Documentation on Dispose() is not always clear. You can assume to get (external) resources released at that point. The rest is "bonus" ;-)
Cheers
Andi
To add to what PIEBALDconsult says, the other advantage of using using is that unlike Close or Dispose, it also limits the scope of the variable to the section of code in which it is valid.
Once you leave the using block, the variable goes out of scope, which means that the compiler will complain if you try to use a variable which has been disposed.

[edit]Typo: "hours" for "goes" (tablet typing) - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Andreas Gieriet 26-Mar-13 18:36pm    
My 5!
Just a small note: since the variable goes out-of-scope, the compiler will complain about unknown variable and not about already disposed object.
Cheers
Andi
OriginalGriff 27-Mar-13 4:43am    
You are right - I should have phrased that better!
To your second question: FxCop has rules to detect missing Dispose() calls.
Depending on your installed Visual Studio flawour, you might have FxCop rules directly available or you might need to run FxCop as a separate build step (e.g. as post build event).
Missing Close() calls go undetected, though, but if the missing Dispose() is detected, a missing Close() is irrelevant.
Cheers
Andi
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900