Quick start manual
Data types, variables, and constants
5-7
Simple types
defines an enumerated type called Suit whose possible values are Club, Diamond,
Heart, and Spade, where Ord(Club) returns 0, Ord(Diamond) returns 1, and so forth.
When you declare an enumerated type, you are declaring each val to be a constant of
type typeName. If the val identifiers are used for another purpose within the same
scope, naming conflicts occur. For example, suppose you declare the type
type TSound = (Click, Clack, Clock);
Unfortunately, Click is also the name of a method defined for TControl and all of the
objects in CLX that descend from it. So if you’re writing an application and you
create an event handler like
procedure TForm1.DBGrid1Enter(Sender: TObject);
var Thing: TSound;
begin
ƒ
Thing := Click;
ƒ
end;
you’ll get a compilation error; the compiler interprets Click within the scope of the
procedure as a reference to TForm’s Click method. You can work around this by
qualifying the identifier; thus, if TSound is declared in MyUnit, you would use
Thing := MyUnit.Click;
A better solution, however, is to choose constant names that are not likely to conflict
with other identifiers. Examples:
type
TSound = (tsClick, tsClack, tsClock);
TMyColor = (mcRed, mcBlue, mcGreen, mcYellow, mcOrange);
Answer = (ansYes, ansNo, ansMaybe);
You can use the (val
1
, ..., val
n
) construction directly in variable declarations, as if it
were a type name:
var MyCard: (Club, Diamond, Heart, Spade);
But if you declare MyCard this way, you can’t declare another variable within the
same scope using these constant identifiers. Thus
var Card1: (Club, Diamond, Heart, Spade);
var Card2: (Club, Diamond, Heart, Spade);
generates a compilation error. But
var Card1, Card2: (Club, Diamond, Heart, Spade);
compiles cleanly, as does
type Suit = (Club, Diamond, Heart, Spade);
var
Card1: Suit;
Card2: Suit;