2.11. 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.
2.11.1. 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 NewFile object is no longer available here.
In this example, as soon as the execution leaves the Using block, the Dispose( ) method is called on the NewFile object, releasing the file handle.
2.11.2. What about...
...errors that occur inside a Using block? Thankfully, .NET makes sure it disposes of the resource no matter how you exit the Using block, even if an unhandled exception occurs.
The Using statement makes sense with all kinds of disposable objects, such as:
2.11.3. Where can I learn more?
For the language lowdown, refer to the index entry "Using block" in the MSDN Help.