13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15 StatementsLocal variables declared in a resource-acquisition are read-only, and must include an initializer. A compiletimeerror occurs if the embedded statement attempts to modify these local variables (via assignment or the++ and -- operators) or pass them as ref or out parameters.A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource isimplicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of theresource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.A using statement of the formusing (ResourceType resource = expression) statementcorresponds to one of two possible expansions. When ResourceType is a value type, the expansion is{ResourceType resource = expression;try {statement;}finally {((IDisposable)resource).Dispose();}}Otherwise, when ResourceType is a reference type, the expansion is{ResourceType resource = expression;try {statement;}finally {if (resource != null) ((IDisposable)resource).Dispose();}}In either expansion, the resource variable is read-only in the embedded statement.A using statement of the formusing (expression) statementhas the same two possible expansions, but in this case ResourceType is implicitly the compile-time type ofthe expression, and the resource variable is inaccessible in, and invisible to, the embedded statement.When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multipleresources of a given type. A using statement of the formusing (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statementis precisely equivalent to a sequence of nested using statements:using (ResourceType r1 = e1)using (ResourceType r2 = e2)...using (ResourceType rN = eN)statement[Example: The example below creates a file named log.txt and writes two lines of text to the file. Theexample 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");}199

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!