Disposable objects and using clauses
Disposable objects are objects that Gosu can dispose to release all system resources. For Gosu to recognize a valid disposable object, the object must have one of the following attributes:
- Implements the Gosu IDisposable interface, which contains only a single method called dispose with no arguments. Use a type that implements IDisposable if possible due to faster runtime performance.
- Has a dispose method with no arguments, even if it does not implement the
IDisposableinterface. This approach is slower at run time, because Gosu must use reflection (examining the type at run time) to find the method.
A type’s dispose method must release all resources owned by its base types by calling its parent type’s dispose method.
To ensure that resources clean up appropriately even under error conditions, you must design your dispose method so Gosu can call it multiple times without throwing an exception, even if the object has already been disposed.
The following example shows a basic disposable object:
// Create a simple disposable class that implements IDisposable
class TestDispose implements IDisposable {
construct(){
print("LOG: Created my object!")
}
override function dispose() {
print("LOG: Disposed of my object! Note that you must support multiple calls to dispose.")
}
}
The following code tests this object:
using (var d = new TestDispose()) {
print("LOG: This is the body of the 'using' statement.")
}
This code prints:
LOG: Created my object!
LOG: This is the body of the 'using' statement.
LOG: Disposed of my object! Note that you must support multiple calls to dispose.
You can pass multiple objects to a using clause. In such cases, exit actions
(closing, disposing, and unlocking) happen in reverse order of the object declarations.
