Defines the start of a unit file - a Delphi module
 keyword Unit(Unit Name;
 end. // Note terminating dot
The Unit keyword is fundamental to Delphi, defining the start of a module.
Each Delphi module is stored in a Name.pas file, where Name must match the Unit Name.
Each unit comprises a set of interface definitions. Do not confuse these with class interfaces - the unit interface is the external interface to the module. It defines to any user of the unit what it contains. These interface definitions define private, protected, public and Published data, types and routine declarations.
Any routines defined in the interface must be implemented in the Implementation section. All function and procedure definitions must have exactly redefined arguments - see procedure and function information.
Optionally, you may have Initialization and Finalization sections. These contain statements executed when the unit is loaded and when it terminates, respectively.
If you only define an Initialization section, you may replace this keyword with Begin.
Related commands
FunctionDefines a subroutine that returns a value
ImplementationStarts the implementation (code) section of a Unit
InterfaceUsed for Unit external definitions, and as a Class skeleton
PrivateStarts the section of private data and methods in a class
ProcedureDefines a subroutine that does not return a value
PropertyDefines controlled access to class fields
ProtectedStarts a section of class private data accesible to sub-classes
PublicStarts an externally accessible section of a class
PublishedStarts a published externally accessible section of a class
 Download this web site as a Windows program.

Example code : A simple example
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.

Unit Unit1;

// External interface to this unit module

  Forms, Dialogs;

  // Define the form class used by this unit
  TForm1 = class(TForm)
    // Define a procedure that must be implemented in the
    // implementation section below
    procedure FormCreate(Sender: TObject);
    { Private declarations }
    { Public declarations }

  // Define a form - can be referenced in the Implementation section
  Form1: TForm1;

// Implements the interface declarations above
{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
  // Set and show the form title
  Form1.Caption := 'Test program';
  ShowMessage('Running = '+Form1.Caption);

  // Tell the user we are starting this unit

Show full unit code
  Running Test program
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page