Jon Jagger
jon@jaggersoft.com
Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specificationpreviousnextprevious at this levelnext at this level 15 Statementsprevious at this levelnext at this level 15.13 The using statement Paragraph 11 The using statement obtains one or more resources, executes a statement, and then disposes of the resource. using-statement : using ( resource-acquisition ) embedded-statement resource-acquisition : local-variable-declaration expression Paragraph 21 A resource is a class or struct that implements System.IDisposable, which includes a single parameterless method named Dispose. 2 Code that is using a resource can call Dispose to indicate that the resource is no longer needed. 3 If Dispose is not called, then automatic disposal eventually occurs as a consequence of garbage collection. Paragraph 31 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. 2 If the form of resource-acquisition is expression then this expression must be System.IDisposable or a type that can be implicitly converted to System.IDisposable. Paragraph 41 Local variables declared in a resource-acquisition are read-only, and must include an initializer. 2 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. Paragraph 51 A using statement is translated into three parts: acquisition, usage, and disposal. 2 Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. 3 This finally clause disposes of the resource. 4 If a null resource is acquired, then no call to Dispose is made, and no exception is thrown. Paragraph 61 A using statement of the form
using (R r1 = new R()) {  
   r1.F();  
}  
is precisely equivalent to
R r1 = new R();  
try {  
   r1.F();  
}  
finally {  
   if (r1 != null) ((IDisposable)r1).Dispose();  
}  
Paragraph 71 A resource-acquisition may acquire multiple resources of a given type. 2 This is equivalent to nested using statements. 3 A using statement of the form
using (R r1 = new R(), r2 = new R()) {  
   r1.F();  
   r2.F();  
}  
is precisely equivalent to:
using (R r1 = new R())  
using (R r2 = new R()) {  
   r1.F();  
   r2.F();  
}  
which is, by expansion, precisely equivalent to:
R r1 = new R();  
try {  
   R r2 = new R();  
   try {  
      r1.F();  
      r2.F();  
   }  
   finally {  
      if (r2 != null) ((IDisposable)r2).Dispose();  
   }  
}  
finally {  
   if (r1 != null) ((IDisposable)r1).Dispose();  
}  
<table_line></table_line>
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS