Using Statements

The using statement executes code that works on a resource that needs to be manually disposed of afterwards. You can thing of it as a convenient combination of a local variabele declaration alongside a try/finally block that makes sure the contents of the variable is disposed proeprly at the end, even if an exception happens:

using fs := new FileStream("textfile.txt", FileMode.Open) do begin
  var b := new byte[123];
  fs.Read(b, 0, b.Length);
end; // the filestream is closed here.

The statement begins with the keyword using, followed by the name of a new variable and an initializer; typically the initializer will create a new object, or call a method that returns a new object, but in theory, any expression is permitted. The do keyword can be followed by a single statement or a begin/end block grouping multiple statements.

At the end of the using statement, the Dispose method wil be called on the object (if it supports disposing). This call is ensured even when an exception occurs, as if it were encapsulated in a try/finally.

Essentially, the above code is equivalent to:

with fs := new FileStream("textfile.txt", FileMode.Open) do try
  var b := new byte[123];
  fs.Read(b, 0, b.Length);
finally
  IDisposable(fs):Dispose(); 
end;

The Disposable Pattern

You can read more about the Disposable Pattern here. Essetially, it centers around an interface (called IDisposable on .NET and the Island-based native platforms, and AutoCloseable in Java, which provides a single method (Dispose or close), which the compiler will automatically call, if the interface is implemented.

Using using on an object that does implement the interface is permitted, but has no effect at runtime. However, this allows you to apply proper precautions when using vlasses that might later change to become disposable.

Auto-Release Pools (Cocoa)

When targetting the Cocoa platform, the using statement has been extended with a special syntax using the autoreleasepool keyword, in order to create new Auto-Release Pool for this thread, and clean it up at the end of the using statement.

Please refer to the Auto-Release Pool topic for more details.

using autoreleasepool do begin
  NSApplicationMain(argc, argv);
end;

Cocoa Only

The using autoreleasepool syntax is relevant and available on the Cocoa platform only.

See Also