Friday, 11 June 2010

Accessing Record’s Elements

After we declare a record ( previous tutorial ), now we are going to access the elements or fields of the record. The fields in a record can be accessed using this notation :

    RecordName.RecordField

Between the field name and the record name separated by a dot.

Example :

program Project1;
{$APPTYPE CONSOLE}
uses
   SysUtils;

type
   TRecordItem = record
     Item : string;
     Quantity : integer;
     Price : currency;
   end;
var
   ItemStock : TRecordItem;

begin
  // assigning values to record's fields
  ItemStock.Item := 'USB Flash Disk';
  ItemStock.Quantity := 20;
  ItemStock.Price := 10;
  // writing teh fields' values.
  writeln('Item : ',ItemStock.Item);
  writeln('Quantity : ',ItemStock.Quantity,' pc/s');
  writeln('Price : $ ',ItemStock.Price:10:2 );
  readln;
end.

Using with statement

With statement allows us to access a record field without mentioning the record name. The syntax of with statement is :

 with Record do
   begin
     statements
   end;

Example :

program Project1;
{$APPTYPE CONSOLE}
uses
   SysUtils;

type
   TRecordItem = record
     Item : string;
     Quantity : integer;
     Price : currency;
   end;
var
ItemStock : TRecordItem;

begin
  with ItemStock do
    begin
      // assigning values to record's fields
      Item := 'USB Flash Disk';
      Quantity := 20;
      Price := 10;
      // writing teh fields' values.
      writeln('Item : ',Item);
      writeln('Quantity : ',Quantity,' pc/s');
      writeln('Price : $ ',Price:10:2 );
    end;
  readln;
end.

You can download the complete code here.

2 comments:

These links are part of a pay per click advertising program called Infolinks. Infolinks is an In Text advertising service; they take my text and create links within it. If you hover your mouse over these double underlined links, you will see a small dialog box containing an advertisement related to the text. You can choose to move the mouse away and go on with your browsing, or to click on the box and visit the relevant ad. Click here to learn more about Infolinks Double Underline Link Ads.