delphitypestypecast-operator

How to save/load Set of Types?


I have this code

type
  TXSample = (xsType1, xsType2, xsType3, xsType4, xsType5, xsType6, xsType6, xsTyp7, xsType8); // up to FXSample30;  
..

private
  FXSample = Set of TXSample;  
..

published
  property Sample: TXSample read FXSample  write FXSample; 
..

  //if Sample has a value of
  Sample := [xsType2, xsType4, xsType5, xsType6, xsTyp7];

how can i save/load the property of Sample?
i would like to save it in the database.
is it possible?


Solution

  • Provided your set will never exceed 32 possibilities (Ord(High(TXSample)) <= 31), then it is perfectly fine to typecast the set into an Integer and back:

    type
      TXSamples = set of TXSample;
    var 
      XSamples: TXSamples;
    begin
      ValueToStoreInDB := Integer(XSamples);
      Integer(XSamples) := ValueReadFromDB;
    end;
    

    To be more specific: SizeOf(TXSamples) has to be precisely equal to SizeOf(StorageTypeForDB). Thus the following ranges apply for Ord(High(TXSample)) when typecasting TXSamples to: