X hits on this document

985 views

0 shares

0 downloads

0 comments

199 / 396

C# LANGUAGE SPECIFICATION

resource-acquisition: local-variable-declaration expression

A resource is a class or struct that implements System.IDisposable, which includes a single parameterless method named Dispose. Code that is using a resource can call Dispose to indicate that the resource is no longer needed. If Dispose is not called, then automatic disposal eventually occurs as a consequence of garbage collection.

If the form of resource-acquisition is local-variable-declaration then the type of the local-variable-declaration must be System.IDisposable or a type that can be implicitly converted to System.IDisposable. If the form of resource-acquisition is expression then this expression must be of type System.IDisposable or a type that can be implicitly converted to System.IDisposable.

Local variables declared in a resource-acquisition are read-only, and must include an initializer. A compile-time error 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 is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

A using statement of the form

using (ResourceType resource = expression) statement

corresponds 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 form

using (expression) statement

has the same two possible expansions, but in this case ResourceType is implicitly the compile-time type of the expression, and the resource variable is inaccessible in, and invisible to, the embedded statement.

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

Document info
Document views985
Page views985
Page last viewedFri Dec 09 04:19:12 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments