tags:

views:

309

answers:

4

I want to do something like this:

const

  MyFirstConstArray: array[0..1] of string = ('Hi', 'Foo');
  MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = 
    MyFirstConstArray + ('Bar');

Basically I want the following result:

MyFirstConstArray -> ('Hi', 'Foo');
MySecondConstArrayWhichIncludesTheFirstOne -> ('Hi', 'Foo', 'Bar');

Is it possible somehow?

A: 

I don't think so. You'll have to do it in code. If these are global constants, you can do the initialization in the 'initialization' section of the unit.

gabr
+2  A: 

AFAIK, you can't do that.
But if the goal is to ensure you declare your actual constant string only once, I suggest you declare the individual strings and then group them in arrays:

const
  MyConst1 = 'Hi';
  MyConst2 = 'Foo';
  MyConst3 = 'Bar';
  MyFirstConstArray: array[0..1] of string = (MyConst1, MyConst2);
  MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = 
    (MyConst1, MyConst2, MyConst3);

BTW, your syntax is incorrect, you have to precise the type of the array elements.

François
I was already doing that, but what I really wanted was to avoid the trouble of updating every array when I add a new item in the first one. But if there's no way of doing this then it can't be helped.
Fabio Gomes
+1  A: 

Actually, you can but do it using records. i use this technique in a big way for creating definitions for certain behaviours of entities in my software. it's a very powerful technique:

type
      TPerson=record
        // generally you'd put all kinds of addition stuff here including enums, 
        // sets, etc
        saPets:array[0..2] of string;
      end;

const
  scDog='Dog';

  MyPeople:array[0..1] of TPerson=
    ((saPets:(scDog, 'Cat', 'Fish'); ),
     (saPets:('Iguana', 'Tarantula', ''); ));

begin
  ShowMessage(MyPeople[0].saPets[0]);

end;

one thing you can't do with it is refer to resource strings. therefore any translation must be done by the code that retrieves the value. i generally index them with enums--in doing so, i can make the software easier to change because it won't compile if i've left something important out.

X-Ray
+1  A: 

If order isn't relevant, then use enumerated sets.

type
  TMyConsts = (tConstFoo, tConstHi, TConstBar);
const
  MyFirstConstSet = [tConstFoo, tConstHi];
  MySecondConstSet = MyFirstConstSet + [TConstBar];
  MyConstStrings: array[TMyConsts] of string = ('Foo', 'Hi', 'Bar');

You can use the MyConstStrings array to resolve your enumerations into strings if you want. Depends on your objective.

Jim McKeeth