Search code examples
arraysdelphiconstantstdictionary

Create a constant array of TDictionary by default value


I want to use the a TDictionary in a Delphi project. But I've a problem,how i can Create a constant array of TDictionary by default value ?

For example i want to allocate 4 item for a dictionary such as bellow code (for constant array of TItem) :

...
type
  TItem = record
    _Key: string;
    _Value: string;
  end;
var
  Dic: array [0..3]of TItem=(
  (_Key:'A' ; _Value:'Apple'),
  (_Key:'B' ; _Value:'Book'),
  (_Key:'C' ; _Value:'C++'),
  (_Key:'D' ; _Value:'Delphi')
  );
...

Is there any way to do this work with TDictionary ? I want to create a constant array of Dic (but) such as bellow structure .

  ...
    var
      Dic: TDictionary<string, string>;
    begin
      Dic := TDictionary<string, string>.Create;
      try
        Dic.Add('A', 'Apple');
        Dic.Add('B', 'Book');
        Dic.Add('C', 'C++');
        Dic.Add('D', 'Delphi');
      finally
         ///
      end;
    ...

Anyone have any advice for me? (Excuse me if my English is poor !)


Solution

  • You cannot write a constant expression that is an instance of a class.

    Yet, since your TDictionary is a collection of String which is a type that you can create constants with, you could just build your TDictionary at run time from your constants. You could use records as in your question, but I like arrays:

    {$IFDEF WHATEVER}
    type
      TDictConstant = array[0..3, 0..1] of String;
    const
      DICT_CONSTANT: TDictConstant = (('A', 'Apple'), ('B', 'Book'), ('C', 'C++'), ('D', 'Delphi'));
    {$ELSE}
    // If you want it "blank" for one config
    type
      TDictConstant = array[0..0, 0..1] of String;
    const
      DICT_CONSTANT: TDictConstant = (('', ''));
    {$ENDIF}
    var
      Dic: TDictionary<string, string>;
    
    procedure TForm1.FormCreate(Sender: TObject);
    var
      i: Integer;
    begin
      Dic := TDictionary<string, string>.Create;
      for i := 0 to High(DICT_CONSTANT) do
      begin
        // Ignore the "blank" ones
        if (DICT_CONSTANT[i][0] <> '') or (DICT_CONSTANT[i][1] <> '') then
        begin
          Dic.Add(DICT_CONSTANT[i][0], DICT_CONSTANT[i][1]);
        end;
      end;
    end;
    

    I've done similar in the past.