Dispose of Objects Automatically
In .NET, it's keenly important to make sure objects that
use unmanaged resources (e.g., file handles, database connections, and
graphics contexts) release these resources as soon as possible. Toward
this end, such objects should always implement the IDisposable interface, and provide a Dispose( ) method that you can call to release
their resources immediately.
Note
Worried that you'll have objects floating around in memory, tying up resources until the garbage collector tracks them down? With the Using statement, you can make sure disposable objects meet with a timely demise.
The only problem with this technique is that you must always
remember to call the Dispose( )
method (or another method that calls Dispose(
), such as a Close( )
method). VB 2005 provides a new safeguard you can apply to make sure
Dispose( ) is always called: the
Using statement.
How do I do that?
You use the Using statement
in a block structure. In the first line, when you declare the Using block, you specify the disposable
object you are using. Often, you'll also create the object at the same
time using the New keyword. Then,
you write the code that uses the disposable object inside the Using block. Here's an example with a
snippet of code that creates a new file and writes some data to the
file:
Using NewFile As New System.IO.StreamWriter("c:\MyFile.txt") NewFile.WriteLine("This is line 1") NewFile.WriteLine("This is line 2") End Using ' The file is closed automatically. ' The ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access