using statements ensures the correct disposal of resources allocated according to the deterministic destruction patern. The using statement can only be used to declare and initialize a local variable with a restricted scope.
There are three variants for the using statement. This variant declares a local variable with an explicitly provided type:
using variable : data-type := expression do statement
A second variant is available where the type for the local variable must be inferred:
using var variable := expression do statement
A third variant doesn't requires a variable:
using expression do statement
When the expression in a using statement header implements the IDisposable interface type, the statement is translated as a resource protection block. If the statement declares a variable and its declared or inferred type is a reference type, this is the translated statement:
var variable: data-type := expression; try statement; finally if variable <> nil then IDisposable(variable).Dispose; end;
When the type of the using variable is a value type, the null test inside the finally clause is dropped. Finally, when there's no variable declaration in the using header, the compiler declares a hidden variable.
Unlike the using statement in C#, you can use types that don't implements IDisposable. In that case, the using statement can be used as a variant of the inline variable declaration, but with a restricted scope. This way, you are not required to know in advance whether a given class or record implements IDisposable or not.
When the variable in a using statement header belongs to a reference type, it is declared read only. Note that Freya doesn't allow explicitly declaring a local variable as read only.
Nested using statements can be merged in a single statement:
using var conn := new SqlConnection(ConnectionStr), var cmnd := new SqlCommand(conn, CommandStr) do cmnd.Execute;
The above statement is expanded by the compiler into two nested using statements:
using var conn := new SqlConnection(ConnectionStr) do using var cmnd := new SqlCommand(conn, CommandStr) do cmnd.Execute;
The Freya Programming Language
Statements
try/finally statements
try/fault statements
try/except statements
raise statements
Expressions