| 1 | = Using = |
| 2 | |
| 3 | Allows IDisposable object acquisition and defines a scope outside of which the the object will be |
| 4 | disposed in the correct manner.[[BR]] |
| 5 | This provides a convenient structure that encapsulates the |
| 6 | correct use and release of an IDisposable object. |
| 7 | |
| 8 | The idiom is that an IDisposable object is acquired/constructed in the '''using''' |
| 9 | statement expression, assigned to a local variable and used within the block. [[BR]] |
| 10 | When the block terminates (for '''any''' reason, fall through, exception or return) |
| 11 | the using statement calls the .dispose method on the object in the correct way,[[BR]] |
| 12 | and also causes the object itself to go out of scope as soon as .dispose is called. [[BR]] |
| 13 | Within the using block, the object is read-only and cannot be modified or reassigned. |
| 14 | |
| 15 | == Grammar == |
| 16 | {{{ |
| 17 | using <name> = <expression> |
| 18 | BLOCK |
| 19 | }}} |
| 20 | |
| 21 | == Platform == |
| 22 | |
| 23 | The above description is couched in terms of .Net |
| 24 | (IDisposable interface, objects supporting a .dispose method for resource release/cleanup). |
| 25 | |
| 26 | The effect is translated to a similarly releasable interface on other platforms. |
| 27 | * Java: |
| 28 | |
| 29 | == Examples == |
| 30 | |
| 31 | {{{ |
| 32 | using 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 | {{{ |
| 40 | using 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 | {{{ |
| 46 | using resultsWriter = File.appendText(resultsFileName) |
| 47 | print to resultsWriter, 'Results of Run [date]' |
| 48 | .printTotals(resultsWriter to !) |
| 49 | }}} |
| 50 | |
| 51 | == Notes == |
| 52 | |
| 53 | You can achieve a similar result by putting the object inside a try |
| 54 | block 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 == |
| 65 | see [http://msdn.microsoft.com/en-us/library/yh598w02.aspx using statement (C# reference)] |
| 66 | |