Ankush
Ankush

Reputation: 89

How to set default value to record in delphi

I am using RAD XE7. In my Delphi application I want to set default values for fields of Records.

I tried following code, but it does not compile, I know it is wrong. I there any another way?

 TDtcData = record
    TableFormat     : TExtTableFormat = fmNoExtendedData;
    DTC             : integer = 0;
    Description     : string = 'Dummy';
    Status          : TDtcStatus;    
    OccurenceCnt    : integer =20;
    FirstDTCSnapShot: integer;
    LastDTCSnapShot: integer;
  end; 

Upvotes: 6

Views: 13738

Answers (2)

nil
nil

Reputation: 1328

With the addition of 'class like' record types in Delphi, you could solve this by using a class function.

Define class function CreateNew: TDtcData; static; for your record.

The implementation sets the default values for the resulting record:

class function TDtcData.CreateNew: TDtcData;
begin
 Result.TableFormat := fmNoExtendedData;
 Result.DTC := 0;
 Result.Description :=  'Dummy';
 Result.OccurenceCnt := 20;
end;

Using this to get a record with the default values like this:

var
  AData: TDtcData;
begin
  AData := TDtcData.CreateNew;;
end.

Upvotes: 5

LU RD
LU RD

Reputation: 34947

If you want to define a partially initialized record, just declare a constant record, but omit those parameters not needing default values:

Type
  TDtcData = record
  TableFormat     : TExtTableFormat;
  DTC             : integer;
  Description     : string;
  Status          : TDtcStatus;
  OccurenceCnt    : integer;
  FirstDTCSnapShot: integer;
  LastDTCSnapShot: integer;
end;

Const
  cDefaultDtcData : TDtcData = 
    (TableFormat : fmNoExtendedData; 
     DTC : 0; 
     Description : 'Dummy'; 
     OccurenceCnt : 20);

var
  someDtcData : TDtcData;
begin
  ...
  someDtcData := cDefaultDtcData;
  ...
end;

Upvotes: 10

Related Questions