
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
188
|
Chapter 3: Classes and Structures
This last point is described by the following code:
FileStream FS;
using(FS = new FileStream("Test.txt", FileMode.Create))
{
FS.WriteByte((byte)1);
FS.WriteByte((byte)2);
FS.WriteByte((byte)3);
using(StreamWriter SW = new StreamWriter(FS))
{
SW.WriteLine("some text.");
}
}
For this example code, you will not have a problem. But consider that the variable FS
is usable outside of the using block. Essentially, you could revisit this code and mod-
ify it as follows:
FileStream FS;
using(FS = new FileStream("Test.txt", FileMode.Create))
{
FS.WriteByte((byte)1);
FS.WriteByte((byte)2);
FS.WriteByte((byte)3);
using(StreamWriter SW = new StreamWriter(FS))
{
SW.WriteLine("some text.");
}
}
FS.WriteByte((byte)4);
This code compiles but throws an ObjectDisposedException on the last line of this
code snippet because the
Dispose method has already been called on the FS object.
The object has not yet been collected at this point and still remains in memory in the
disposed state.
See Also
See Recipes 3.29 and 3.31; see the “IDispose Interface,” “Using foreach with Collec-
tions,” and “Implementing Finalize and Dispose to Clean up Unmanaged Resources”
topics in the MSDN documentation.
3.28 Releasing a COM Object Through Managed Code
Problem
You need to release a COM object ...