Information Technology Reference
In-Depth Information
Multiple Resources and Nesting
The using statement can also be used with multiple resources of the same type, with the
resource declarations separated with commas. The syntax is the following:
Only one type
using ( ResourceType Id1 = Expr1, Id2 = Expr2, ... ) EmbeddedStatement
For example, in the following code, each using statement allocates and uses two
resources.
static void Main()
{
using (TextWriter tw1 = File.CreateText("Lincoln.txt"),
tw2 = File.CreateText("Franklin.txt"))
{
tw1.WriteLine("Four score and seven years ago, ...");
tw2.WriteLine("Early to bed; Early to rise ...");
}
using (TextReader tr1 = File.OpenText("Lincoln.txt"),
tr2 = File.OpenText("Franklin.txt"))
{
string InputString;
while (null != (InputString = tr1.ReadLine()))
Console.WriteLine(InputString);
while (null != (InputString = tr2.ReadLine()))
Console.WriteLine(InputString);
}
}
Another characteristic of using statements is that they can be nested. For example, in the
following code, there are two things to notice—besides the nesting of the using statements,
also note that it is not necessary to use a block with the second using statement because it con-
sists of only a single, simple statement.
using (TextWriter tw1 = File.CreateText("Lincoln.txt"))
{
tw1.WriteLine("Four score and seven years ago, ...");
using( TextWriter tw2 = File.CreateText("Franklin.txt")) // Nested
tw2.WriteLine("Early to bed; Early to rise ..."); // Single
}
Search WWH ::




Custom Search