Delphi – How to declare a fixed value in a record

delphi

I would like to know how do I declare a record, that has some fixed values. I need to send data using this pattern: Byte($FF)-Byte(0..250)-Byte(0..250). I am using record for that and I would like to have the first value of it constant, so that it can't be messed up.
Such as:

TPacket = record
  InitByte: byte; // =255, constant
  FirstVal,
  SecondVal: byte;
end;

Best Solution

You can't rely on a constructor because, contrary to Classes, Records are not required to use them, the default parameterless constructor being used implicitly.

But you can use a constant field:

type
  TPacket = record
   type
     TBytish = 0..250;
   const
     InitByte : Byte = 255;
   var
     FirstVal,
     SecondVal: TBytish;
  end;

Then use this as a regular Record, except that you don't have (and you can't) change the InitByte field.
FillChar preserves the constant field and behaves as expected.

procedure TForm2.FormCreate(Sender: TObject);
var
  r: TPacket;
begin
  FillChar(r, SizeOf(r), #0);
  ShowMessage(Format('InitByte = %d, FirstVal = %d, SecondVal = %d', [r.InitByte, r.FirstVal,r.SecondVal]));
  // r.InitByte := 42;  // not allowed by compiler
  // r.FirstVal := 251; // not allowed by compiler
  r.FirstVal := 1;
  r.SecondVal := 2;
  ShowMessage(Format('InitByte = %d, FirstVal = %d, SecondVal = %d', [r.InitByte, r.FirstVal,r.SecondVal]));
end;

Updated to include the nested type range 0..250

Related Question