DelphiBasics
Is
Keyword
Tests whether an object is a certain class or ascendant
  Object reference Is Class reference
Description
The Is keyword is used to test to see whether an object belongs to a class, or parent of that class.
 
For example, you may test to see whether a graphical component (normally called 'Sender') is a TButton, or TList or whatever.
 
All objects belong to the TObject class, from which they are ultimately derived.
Related commands
As Used for casting object references
Class Starts the declaration of a type of object class
Object Allows a subroutine data type to refer to an object method
TObject The base class type that is ancestor to all other classes
 Author links

 Download this web site as a Windows program.





 
Example code : Illustrate use of is on a class hierarchy
// 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;

interface

uses
  Forms, Dialogs, Classes, Controls, StdCtrls;

type
  // Define new class types
  TFruit = class
  public
    name : string;
  published
    constructor Create(name : string);
  end;
  // Define two descendant types
  TApple = class(TFruit);
  TPear  = class(TFruit);
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation
{$R *.dfm} // Include form definitions

// Create a fruit object
constructor TFruit.Create(name: string);
begin
  self.name := name;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  fruit  : TFruit;
  apple  : TApple;
  pear   : TPear;
begin
  // Create 2 different fruit objects
  apple  := TApple.Create('Pink Lady');
  pear   := TPear.Create('Comice');

  // They are both TFruit or descendant types
  if apple  Is TFruit then ShowMessage(apple.name +' is a fruit');
  if pear   Is TFruit then ShowMessage(pear.name  +' is a fruit');

  // Apple is also a TApple type
  fruit := apple;
  if fruit Is TApple then ShowMessage(apple.name  +' is an apple');

  // But apple is not a pear
  if fruit Is TPear    // 'if apple is TPear' does not compile
  then ShowMessage(apple.name+' is a pear')
  else ShowMessage(apple.name+' is not a pear');
end;
end.
   Pink lady is a fruit
   Comice is a fruit
   Pink lady is an apple
   Pink lady is not a pear
 
Delphi Programming Neil Moffatt 2002 - 2020. All rights reserved.  |  Home Page