Now, this one has been bugging me for some time, and I have never actually sat down to investigate it, so I thought I should. I have been told on several occasions that I should use "using", but when questioning why, I get no real answer that makes any sense. Seems like a classic "every knows the best practice but doesn't understand the practice or why its best" scenario!
So, I made some very small code samples, one using "using" the other using Dispose(). Here are the samples FYI:
As you can see, nothing fancy! And here are the results (intermediate language - "IL") courtesy of ILDASM:
So, as you can see, the "using" method wraps the code inside the scope of the statement within a "try" block of a "try/finally", placing the Dispose() call in the finally, meaning it will always get executed even if an Exception is thrown. However, using the explicit Dispose() method, if an Exception is thrown, then it will not get disposed of, meaning it could be sat on the heap for a few milliseconds or even a few minutes, not good!
I guess this is why MSDN refers to the "using" statement as the "convenient syntax for correct use of IDisposable objects".
I believe the VB developers out there do not have an equivalent available, so make sure you are wrapping all of your disposable objects calls in try/finally blocks!
Update: I have been told that VB.NET 2.0 does actually have a "using" statement as well, which looks surprisingly like the C# syntax! http://msdn.microsoft.com/en-us/library/htd05whh.aspx
Share: digg it! | del.icio.us | furl | Live | Technorati | Facebook