X hits on this document

1253 views

0 shares

0 downloads

0 comments

200 / 396

Chapter ‎18   Unsafe code

When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multiple resources of a given type. A using statement of the form

using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement

is precisely equivalent to a sequence of nested using statements:

using (ResourceType r1 = e1) using (ResourceType r2 = e2) ... using (ResourceType rN = eN) statement

The example below creates a file named log.txt and writes two lines of text to the file. The example then opens that same file for reading and copies the contained lines of text to the console.

using System; using System.IO;

class Test { static void Main() { using (TextWriter w = File.CreateText("log.txt")) { w.WriteLine("This is line one"); w.WriteLine("This is line two"); }

using (TextReader r = File.OpenText("log.txt")) { string s; while ((s = r.ReadLine()) != null) { Console.WriteLine(s); }

} } }

Since the TextWriter and TextReader classes implement the IDisposable interface, the example can use using statements to ensure that the underlying file is properly closed following the write or read operations.

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.187

Document info
Document views1253
Page views1253
Page last viewedFri Jan 20 08:11:34 UTC 2017
Pages396
Paragraphs9401
Words133190

Comments