Home > Articles

0672320606

  • Print
  • + Share This

Records

Records are a technique for binding together multiple data types into a single structure. Examples of using records can be found in the RecordWorks program found in the Chap03 directory of your accompanying CD.

Consider the following method:

procedure TForm1.Button1Click(Sender: TObject);
var
  FirstName: String;
  LastName: String;
  Address: String;
  City: String;
  State: String;
  Zip: String;
begin
  FirstName := `Blaise';
  LastName := `Pascal';
  Address := `1623 Geometry Lane';
  City := `Clemont';
  State := `CA';
  Zip := `81662'
end;

The String declarations in the var section are all part of an address. Here is how you can bind these identifiers into one record:

procedure TForm1.Button2Click(Sender: TObject);
type
  TAddress = record
    FirstName: String;
    LastName: String;
    Address: String;
    City: String;
    State: String;
    Zip: String;
  end;
var
  Address: TAddress;
begin
  Address.FirstName := `Blaise';
  Address.LastName := `Pascal';
  Address.Address := `1623 Geometry Lane';
  Address.City := `Clemont';
  Address.State := `CA';
  Address.Zip := `81662'
end;

In this second example, a record declaration has been added to the type section of the Button2Click method. A variable of type TAddress has been declared in the var section. Dot notation is used in the body of the Button2Click method to enable you to reference each field of the record: Address.FirstName. People often will read out loud such a declaration as "Address dot FirstName," hence the term dot notation.

C/C++ NOTE

A record in Object Pascal is the same thing as a struct in C/C++. However, in C/C++, the line between a struct and an object is blurred, while in Object Pascal they are two distinctly different types. Pascal records do not support the concept of a method, although you can have a pointer to a method or function as a member of a record. However, that pointer references a routine outside the record itself. A method, on the other hand, is a member of an object.

Records and with Statements

You can create a with statement to avoid the necessity of using dot notation to reference the fields of your record. Consider the following code fragment:

procedure TForm1.Button3Click(Sender: TObject);
type
  TPerson = Record
    Age: Integer;
    Name: String;
  end;
var
  Person: TPerson;
begin
  with Person do begin
    Age := 100046;
    Name := `ET';
  end;
end;

The line with Person do begin is a with statement that tells the compiler that the identifiers Age and Name belong to the TPerson record. In effect, with statements offer a kind of shorthand to make it easier to use records or objects.

NOTE

with statements are a double-edged sword. If used properly, they can help you write cleaner code that's easier to understand. If used improperly, they can help you write code that not even you can understand. Frankly, I tend to avoid the syntax because it can be so confusing. In particular, the with syntax can break the connection between a record or object and the fields of that record or object.

For instance, you have to use a bit of reasoning to realize that Age belongs to the TPerson record and is not, for instance, simply a globally scoped variable of type Integer. In this case, the true state of affairs is clear enough, but in longer, more complex programs, it can be hard to see what has happened. A good rule of thumb might be to use with statements if they help you write clean code and then to avoid them if you are simply trying to save time by cutting down on the number of keystrokes you type.

Variant Records

A variant record in Pascal enables you to assign different field types to the same area of memory in a record. In other words, one particular location in a record could be either of type A or of type B. This can be useful in either/or cases, where a record can have either one field or the other field, but not both. For instance, consider an office in which you track employees either by their name or by an ID, but never by both at the same time. Here is a way to capture that idea in a variant record:

procedure TForm1.VariantButtonClick(Sender: TObject);
type
  TMyVariantRecord = record
    OfficeID: Integer;
    case PersonalID: Integer of
      0: (Name: ShortString);
      1: (NumericID: Integer);
  end;
var
  TomRecord, JaneRecord: TMyVariantRecord;
begin
  TomRecord.Name := `Sammy';
  JaneRecord.NumericID := 42;
end;

The first field in this record, OfficeID, is just a normal field of the record. I've placed it there just so you can see that a variant record can contain not only a variant part, but also as many normal fields as you want.

The second part of the record, beginning with the word case, is the variant part. In this particular record, the PersonalID can be either a String or an Integer, but not both. To show how this works, I declare two records of type TMyVariantRecord and then use the Name part of one variant record and the NumericID of the other record instance.

Name and NumericID share the same block of memory in a TVariantRecord—or, more precisely, they both start at the same offset in the record. Needless to say, a String takes up more memory than an Integer. In any one instance of the record at any one point in time, you can have either the String or the Integer, but not both. Assigning a value to one or the other field, will, at least in principle, overwrite the memory in the other field.

The compiler will always allocate enough memory to hold the largest possible record that you can declare. For instance, in this case, it will always allocate 4 bytes for the field OfficeID and then 256 bytes for the String, giving you a total of 260 bytes for the record. This is the case even if you use only the OfficeID and NumericID fields, which take up only 8 bytes of memory.

For me, the most confusing part of variant records is the line that contains the word case. This syntax exists to give you a means of telling whether the record uses the NumericID or the Name field. Listing 3.4 shows a second example that focuses on how to use the case part of a variant record.

Listing 3.4  The case Part of a Variant Record Used in the ShowRecordType Method

unit Main;

interface

uses
  Windows, Messages, SysUtils,
  Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls;

type
  TMyVariantRecord = record
    OfficeID: Integer;
    case PersonalID: Integer of
      0: (Name: ShortString);
      1: (NumericID: Integer);
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    procedure ShowRecordType(R: TMyVariantRecord);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.ShowRecordType(R: TMyVariantRecord);
begin
  case R.PersonalID of
    0: ShowMessage(`Uses Name field: ` + R.Name);
    1: ShowMessage(`Uses NumericID: ` + IntToStr(R.NumericID));
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Sam, Sue: TMyVariantRecord;
begin
  Sam.OfficeID := 1;
  Sue.PersonalID := 0;
  Sue.Name := `Sue';
  ShowRecordType(Sue);
  Sam.OfficeID := 2;
  Sam.PersonalID := 1;
  Sam.NumericID := 1;
  ShowRecordType(Sam);
end;

end.

In this example, the two records are passed into the ShowRecordType method. One record has the PersonalID set to 0; the other has it set to 1. ShowRecordType uses this information to sort out whether any one particular record uses the Name field or the RecordID field:

  case R.PersonalID of
    0: ShowMessage(`Uses Name field: ` + R.Name);
    1: ShowMessage(`Uses NumericID: ` + IntToStr(R.NumericID));
  end;

As you can see, if PersonalID is set to 0, the Name field is valid; if it is set to 1, the NumericID field is valid.

NOTE

A case statement plays the same role in Object Pascal that switch statements play in C/C++ and Java. Other than the obvious syntactical similarities, there is no significant connection between the case part of a variant record and case statements. In and of themselves, case statements have nothing to do with variant records. It is simply coincidence that, in this example, case statements are the best way to sort out the two different types of records that can be passed to the ShowRecordType procedure. The following code, however, would also get the job done:

procedure TForm1.ShowRecordType2(R: TMyVariantRecord);
begin
  if R.PersonalID = 0 then
    ShowMessage(`Uses Name field: ` + R.Name)
  else
    ShowMessage(`Uses NumericID: ` + IntToStr(R.NumericID));
end;

Here is one last variant record that shows how far you can press this paradigm:

procedure TForm1.HonkerButtonClick(Sender: TObject);
type
  TAnimalType = (atCat, atDog, atPerson);
  TFurType = (ftWiry, ftSoft);
  TMoodType = (mtAggressive, mtCloying, mtGoodNatured);
  TAnimalRecord = record
    Name: String;
    Age: Integer;
    case AnimalType: TAnimalType of
      atCat: (Talk: ShortString;
            Fight: ShortString;
            Food: ShortString);
      atDog: (Fur: TFurType;
            Description: ShortString;
            Mood: TMoodType);
      atPerson:(Rank: ShortString;
             SerialNumber: ShortString);
  end;

var
  Cat, Dog, Person: TAnimalRecord;
begin
  Cat.Name := `Valentine';
  Cat.Age := 14;
  Cat.Talk := `Meow';
  Cat.Fight := `Scratch';
  Cat.Food := `Cheese';
  Dog.Name := `Rover';
  Dog.Age := 2;
  Dog.AnimalType := atDog;
  Dog.Fur := ftWiry;
  Dog.Description := `Barks';
  Dog.Mood := mtGoodNatured;
end;

In this example, I declare an enumerated type named TAnimalType. I use this type in the case part of the variant record, which enables me to use descriptive names rather than numbers for each case:

  TAnimalType = (atCat, atDog, atPerson);
  TAnimalRecord = record
    case AnimalType: TAnimalType of
      atCat:
      atDog:
      atPerson:
  end;

The other important bit of code in this example is the fact that you can place multiple fields in each element of the case part:

atDog: (Fur: TFurType;
        Description: ShortString;
        Mood: TMoodType);

Here you can see that the atDog part of the variant records has three separate fields: Fur, Description, and Mood.

NOTE

I use ShortStrings in these examples because you cannot use the system-allocated variables of type AnsiStrings, WideStrings, dynamic arrays, or Interfaces in a variant record. However, you can use pointers to these forbidden types.

Variant records don't play a large role in Object Pascal programming. However, they are used from time to time in some fairly crucial places, and they fit nicely into our search for the more advanced parts of the language that might not be obvious at first glance to a newcomer. In fact, I've seen many experienced Pascal programmers get tripped up by this syntactically complex entity.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.