Search code examples
delphidelphi-2007

Delphi 2007 variant type initialization


I am trying to declare a constant array for validating type properties held by input object. but i am doing something incorrect, please have a look at below code:

// Record to hold Name-Value pair for checking entities  
TValues = record  
  Name : WideString;  
  Value : Variant;  
end;  

const  
 coarrType1Properties : array[0..5] of TValues =  
 (  
  (Name : 'HARDWARE'; Value : TRUE),  
  (Name : 'SOFTWARE'; Value : TRUE),  
  (Name : 'TAG'; Value : TRUE),  
  (Name : 'AUTHORIZED'; Value : TRUE),  
  (Name : 'ID'; Value : 700),  
  (Name : 'CODE'; Value : 0)  
 );  

but I am getting delphi compile time error for type value i.e. This type cannot be initialized. How to prevent this error? Or can we have alternate solution etc. Please assist...


Solution

  • For these (Boolean, Integer) and other simple types, you could initialize with TVarData and typecast back to Variant:

    type
      TValues = record
        Name: WideString;
        Value: TVarData;
      end;
    
    const
      coarrType1Properties : array[0..5] of TValues = (
        (Name: 'HARDWARE'; Value: (VType: varBoolean; VBoolean: True)),
        (Name: 'SOFTWARE'; Value: (VType: varBoolean; VBoolean: True)),
        (Name: 'TAG'; Value: (VType: varBoolean; VBoolean: True)),
        (Name: 'AUTHORIZED'; Value: (VType: varBoolean; VBoolean: True)),
        (Name: 'ID'; Value: (VType: varInteger; VInteger: 700)),
        (Name: 'CODE'; Value: (VType: varInteger; VInteger: 0))
      );
    
    procedure Test;
    var
      I: Integer;
    begin
      for I := Low(coarrType1Properties) to High(coarrType1Properties) do
        Writeln(Format('coarrType1Properties[%d]: ''%s'', %s', [I, coarrType1Properties[I].Name, VarToStr(Variant(coarrType1Properties[I].Value))]));
    end;