Information Technology Reference
In-Depth Information
Example of the using Statement
The following code uses the
using
statement twice—once with a class called
TextWriter
, and
once with a class called
TextReader
, both from the
System.IO
namespace. Both classes imple-
ment the
IDisposable
interface, as required by the
using
statement.
The
TextWriter
resource opens a text file for writing and writes a line to the file.
The
TextReader
resource then opens the same text file, and reads and displays the con-
tents, line by line.
In both cases, the
using
statement makes sure that the objects'
Dispose
methods
are called.
Notice also the difference between the
using
statements in
Main
and the
using
directives
on the first two lines.
using System; // using DIRECTIVE; not using statement
using System.IO; // using DIRECTIVE; not using statement
namespace UsingStatement
{
class Program
{
static void Main( )
{
// using statement
using (TextWriter tw = File.CreateText("Lincoln.txt") )
{
tw.WriteLine("Four score and seven years ago, ...");
}
// using statement
using (TextReader tr = File.OpenText("Lincoln.txt"))
{
string InputString;
while (null != (InputString = tr.ReadLine()))
Console.WriteLine(InputString);
}
}
}
}
This code produces the following output:
Four score and seven years ago, ...