Wiki

Changes between Initial Version and Version 1 of Using

Show
Ignore:
Timestamp:
05/05/10 11:09:13 (15 years ago)
Author:
hopscc
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Using

    v1 v1  
     1= Using =  
     2 
     3Allows  IDisposable object acquisition and defines a scope outside of which the the object will be  
     4disposed in the correct manner.[[BR]] 
     5This provides a convenient structure that encapsulates the  
     6correct use and release of an IDisposable object. 
     7 
     8The idiom is that an IDisposable object  is acquired/constructed in the '''using'''  
     9statement expression, assigned to a local variable and used within the block. [[BR]] 
     10When the block terminates (for '''any''' reason, fall through, exception or return) 
     11the using statement calls the .dispose  method on the object in the correct way,[[BR]]  
     12and also causes the object itself to go out of scope as soon as .dispose is called. [[BR]] 
     13Within the using block, the object is read-only and cannot be modified or reassigned. 
     14 
     15== Grammar == 
     16{{{ 
     17using <name> = <expression>  
     18    BLOCK 
     19}}} 
     20 
     21== Platform == 
     22 
     23The above description is couched in terms of .Net  
     24(IDisposable interface, objects supporting a .dispose method for resource release/cleanup). 
     25 
     26The effect is translated to a similarly releasable interface on other platforms. 
     27  * Java:  
     28 
     29== Examples == 
     30 
     31{{{ 
     32using font1 = new Font("Arial", 10.0f)  
     33    charset = font1.GdiCharSet 
     34    # do domething with charset 
     35# font1 disposed of (and out of scope) here 
     36}}} 
     37 
     38 
     39{{{ 
     40using f = File.createText(scriptName) 
     41    f.writeLine('#!/bin/sh') 
     42    f.writeLine('echo "Running a shell script made from cobra-[CobraCore.version]" "$@"') 
     43}}} 
     44 
     45{{{ 
     46using resultsWriter = File.appendText(resultsFileName) 
     47    print to resultsWriter, 'Results of Run [date]' 
     48    .printTotals(resultsWriter to !) 
     49}}} 
     50 
     51== Notes == 
     52 
     53You can achieve a similar result by putting the object inside a try 
     54block and then calling .dispose in a finally block 
     55{{{ 
     56  font1 = new Font("Arial", 10.0f) 
     57  try 
     58    charset = font1.GdiCharSet 
     59    # do domething with charset 
     60  finally 
     61    if font1, (font1 to IDisposable).dispose 
     62}}} 
     63 
     64== See Also == 
     65see [http://msdn.microsoft.com/en-us/library/yh598w02.aspx using statement (C# reference)] 
     66