Chapter 7: User-Defined Types


Custom data types are used very often in programming because they are more descriptive than standard data types and because their usage results in cleaner code. This is especially true for records. But before we learn how to create and use records, we have to understand how to create and use enumerated types, subrange types, and sets.

Enumerated Types

An enumerated type is an ordered list of identifiers and is a good replacement for a collection of constants. For instance, the following constants can be replaced with an enumeration:

const   PAWN = 1;   ROOK = 2;   KNIGHT = 3;   BISHOP = 4;   QUEEN = 5;   KING = 6;

The syntax for declaring an enumerated type is:

type   TEnumeratedType = (value_1, value_2, value_n);   TChessFigure = (cfPawn, cfRook, cfKnight,     cfBishop, cfQueen, cfKing);

By using a TChessFigure variable instead of an integer, the code is easier to read and it enables Delphi to perform type checking. Each identifier in the enumeration gets an ordinal value. The ordinal values in the enumeration start at zero. So, Ord(cfPawn) = 0.

All ordinal procedures and functions can work with enumerated types. You can also explicitly define the ordinal value of an enumeration element:

type   TOddNumber = (oddFirst = 1, oddSecond = 3,     oddThird = 5, oddFourth = 7);   TEvenNumber = (evFirst = 0, evSecond = 2,     evThird = 4, evFourth = 6); var   OddNum: TOddNumber; begin   OddNum := oddThird;   WriteLn(Ord(OddNum)); { 5 }   ReadLn; end.



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net