Here's a little Delphi 101 trick for
creating pre-initialized arrays.
Instead of coding this:
1
2 var
3 myArray: array[0..2] of string;
4
5 procedure FillArray;
6 begin
7 myArray[0] := 'Test1';
8 myArray[1] := 'Test2';
9 myArray[2] := 'Test3';
10 end;
11
12
13 {you can pre-initialize an array,
14 by declaring it as a constant.
15 Here's the syntax:}
16
17 const
18 myArray: array[0..2] of string =
19 ('Test1','Test2','Test3');
I've included a slightly more complicated
example, which uses records as the elements
of the array.
Here is the sample
20
21 unit InitializingArrays_Demo;
22
23 interface
24
25 uses
26 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
27 Dialogs, StdCtrls;
28
29 type
30 TForm1 = class(TForm)
31 Button1: TButton;
32 procedure Button1Click(Sender: TObject);
33 private
34 { Private declarations }
35 public
36
37 end;
38
39 var
40 Form1: TForm1;
41
42 implementation
43
44 uses
45 InitializingArrays;
46
47 {$R *.dfm}
48
49 procedure TForm1.Button1Click(Sender: TObject);
50 var
51 myDog: TDog;
52 begin
53 myDog := Dogs[0];
54 ShowMessage('My dog''s name is: ' + myDog.Name);
55 end;
56
57 end.
58
59 //Now this is the unit that creates the array
60
61 unit InitializingArrays;
62
63 interface
64
65 type
66 TDogBreed = (dbTerrier, dbSchnauzer, dbChihuahua, dbPoodle);
67
68 TDog = record
69 UID: Integer;
70 Name: string;
71 Breed: TDogBreed;
72 end;
73
74
75 const
76 Dogs: array [0..3] of TDog = (
77 (UID: 1000; Name: ('Fluffy'); Breed: dbPoodle),
78 (UID: 1001; Name: ('Karl'); Breed: dbSchnauzer),
79 (UID: 1002; Name: ('Scraps'); Breed: dbTerrier),
80 (UID: 1003; Name: ('Enrique'); Breed: dbChihuahua)
81 );
82
83 implementation
84
85 end.
|