Home  |  Delphi .net Home  |  System.Object  |  Finalize Method
  
Finalize  
Method  
A method called when an object is about to be released
Object Class
System NameSpace
CF1.  Procedure Finalize ;
CF : Methods with this mark are Compact Framework Compatible
Description
The Finalize method is called when an object is no longer used (accessible) and is about to be garbage collected. It allows the class to free up resources it has used.
Notes
The Finalize method call may not happen until your program has all but ended - and after the last Console.Writeline call in the example - since the Common Language Runtime Garbage Collection is independent of the program flow.

Since you are overriding the base Object Finalize method, you must add the override; clause.
Microsoft MSDN Links
System
System.Object
 Author links

 Buy Website Traffic at
 Buywebsitetrafficexperts.com

 Buy Proxies at
 Buyproxies.io
 
 
 
Showing how to code a Finalize method
program Project1;
{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  // Define a new class inherited from Object
  MyClass = Class(System.Object)

    private
      OsVersion : Version;

    strict protected
      Procedure Finalize; override;

    Published
      Constructor Create; overload;
  end;

// MyClass constructor
Constructor MyClass.Create;
begin
  inherited;

  // Allocate an object
  OsVersion := Version.Create(1,2,3,4);
end;

// MyClass finalizer
Procedure MyClass.Finalize;
begin
  Console.WriteLine('Finalize called');

  // Free up the object
  FreeAndNil(OsVersion);

  inherited;
end;

// Use this new class
var
  TestObject : MyClass;

begin
  // Create the test class
  TestObject := MyClass.Create;
  Console.WriteLine('MyClass object created');

  // Free it
  TestObject.Free;
  Console.WriteLine('MyClass object freed');
  Console.WriteLine('Note that finalize is actually called at program end');

  Console.ReadLine;
end.
   MyClass object created
   MyClass object freed
   Note that finalize is actually called at program end
 
 
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Contact the author