Destructors
Syntax
Destructors use the ~TypeName() syntax and are called automatically when a stack-allocated value goes out of scope:
type Resource{ int handle;
Resource(int h) { this.handle = h; }
~Resource() { this.handle = 0; }}
{ Resource r(42); // ... use r ...} // ~Resource() called hereRules
- No parameters allowed
- Called automatically at end of scope
- Called in reverse order of declaration (LIFO)
- Only applies to stack-allocated value type variables
Multiple Variables
When multiple destructible variables exist in the same scope, they are destroyed in reverse declaration order:
type Logger{ int id; Logger(int i) { this.id = i; } ~Logger() { Console.WriteLine($"{this.id}"); }}
{ Logger a(1); Logger b(2); Logger c(3);}// Output: 3, 2, 1Inheritance
Derived destructors run before base destructors:
type Base{ ~Base() { Console.WriteLine("~Base"); }}
type Derived : Base{ ~Derived() { Console.WriteLine("~Derived"); }}
{ Derived d;}// Output: ~Derived, ~BaseEarly Returns
Destructors are called on all exit paths, including early returns:
int DoWork(){ Resource r(1); if (true) { return 42; // ~Resource() called before return } return 0; // ~Resource() called here too}