Using
Allows IDisposable object acquisition and defines a scope outside of which the the object will be
disposed in the correct manner.
This provides a convenient structure that encapsulates the
correct use and release of an IDisposable object.
The idiom is that an IDisposable object is acquired/constructed in the using
statement expression, assigned to a local variable and used within the block.
When the block terminates (for any reason, fall through, exception or return)
the using statement calls the .dispose method on the object in the correct way,
and also causes the object itself to go out of scope as soon as .dispose is called.
Within the using block, the object is read-only and cannot be modified or reassigned.
Grammar
using <name> = <expression> <statements>
Platform
The above description is couched in terms of .Net (IDisposable interface, objects supporting a .dispose method for resource release/cleanup).
The effect is translated to a similarly releasable interface on other platforms.
- Java:
Examples
using font1 = new Font("Arial", 10.0f) charset = font1.GdiCharSet # do domething with charset # font1 disposed of (and out of scope) here
using f = File.createText(scriptName) f.writeLine('#!/bin/sh') f.writeLine('echo "Running a shell script made from cobra-[CobraCore.version]" "$@"')
using resultsWriter = File.appendText(resultsFileName) print to resultsWriter, 'Results of Run [date]' .printTotals(resultsWriter to !)
Notes
You can achieve a similar result by putting the object inside a try block and then calling .dispose in a finally block
font1 = new Font("Arial", 10.0f) try charset = font1.GdiCharSet # do domething with charset finally if font1, (font1 to IDisposable).dispose