Using


To make it easy to call an object’s Dispose method, you can declare a variable in a Using statement. When the code reaches the corresponding End Using statement, Visual Basic automatically calls the object’s Dispose method.

You can only place Using statements inside code blocks, not at the module level, so the syntax is somewhat simpler than the syntax for declaring a variable in general. The following code shows the syntax for declaring a variable in a Using statement:

  Using name [(bounds_list)] [As [New] type] [= initialization_expression] ... End Using 

The parts of this statement are described in the previous section.

If it declares the variable, the Using statement must also initialize either with the As New syntax or with an initialization expression.

Note that you can also use a Using statement to make it easier to call a previously created object’s Dispose method. The following code defines the thick_pen object, and then is used in a Using statement.

  Dim thick_pen As New Pen(Color.Red, 10) Using thick_pen ... End Using 

With this technique, the variable is available outside of the Using block, which may occasionally lead to confusion, so I recommend declaring variables in their Using blocks whenever possible.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net