
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Assuring an Object’s Disposal
|
187
Discussion
The using statement is very easy to use and saves you the hassle of writing extra
code. If the Solution had not used the
using statement, it would look like this:
FileStream FS = new FileStream("Test.txt", FileMode.Create);
try
{
FS.WriteByte((byte)1);
FS.WriteByte((byte)2);
FS.WriteByte((byte)3);
StreamWriter SW = new StreamWriter(FS);
try
{
SW.WriteLine("some text.");
}
finally
{
if (SW != null)
{
((IDisposable)SW).Dispose( );
}
}
}
finally
{
if (FS != null)
{
((IDisposable)FS).Dispose( );
}
}
Several points to note about the using statement:
• There is a
using directive, such as
using System.IO;
which should be differentiated from the using statement. This is potentially con-
fusing to developers first getting into this language.
• The variable(s) defined in the
using statement clause must all be of the same
type, and they must have an initializer. However, you are allowed multiple
using
statements in front of a single code block, so this isn’t a significant restriction.
• Any variables defined in the
using clause are considered read-only in the body of
the
using statement. This prevents a developer from inadvertently switching the
variable to refer to a different object and causing problems when an attempt is
made to dispose of the object that the ...