Information Technology Reference
In-Depth Information
Packaging Use of the Resource
The
using
statement helps reduce the potential problem of an unexpected runtime error by
neatly packaging the use of a resource.
There are two forms of the
using
statement. The first form is the following, and is illus-
trated in Figure 9-11.
The code between the parentheses allocates the resource.
The
Statement
is the code that uses the resource.
The
using
statement
implicitly generates
the code to dispose of the resource.
using (
ResourceType Identifier = Expression
)
Statement
↑
↑
Allocates resource
Uses resource
Unexpected runtime errors are called
exceptions
, and are covered in Chapter 11. The stan-
dard way of handling the possibility of exceptions is to place the code that might cause an
exception in a
try
block, and place any code that
must
be executed, whether or not there is an
exception, into a
finally
block.
This form of the
using
statement does exactly that. It performs the following:
Allocates the resource
Places the
Statement
in a
try
block
Creates a call to the resource's
Dispose
method and places it in a
finally
block.
Figure 9-11.
The effect of the using statement