Using Statement

You can use a Using statement to ensure that unmanaged resources are disposed of properly. Recall from Chapter 3 that you do not need to track and manage the memory resources for your application because the garbage collector reclaims any memory that is no longer being used. However, if you want to ensure that unmanaged resources are properly disposed of, or if you are using a managed resource that uses a lot of memory, you can use a Using block to ensure that the resource is disposed of whenever the block is exited.

In the Using block, you specify the resources that you want to manage. You use the End Using statement to indicate that you are no longer using the resource and that the system can dispose of any resources that were controlled by the Using block. Listing 4.5 shows how to use the Using statement with a SQL database. You should always close a SQLConnection by calling Close or Dispose, but when you declare the connection within a Using statement, it ensures that the Dispose method is called for you. The example assumes that the string Connection is a valid connection string.

Listing 4.5. A Using block manages a resource. Sub SampleCode(ByVal Connection As String)

Using sqlConnection As New System.Data.SqlClient. _ SqlConnection(Connection)

'Add code to open connection and work with data. End Using End Sub

0 0

Post a comment