Author: Jeff Guidotti
Wouldn't it be much easier to enter AStringList[Index] instead of
AStringList.Strings[Index]? Well you can, and you can add this functionality to
your own classes.
This may be obvious to some, but it's also something that I haven't come across
until now, so I figured it might be useful to someone out there.
For many array properties found in classes in delphi, you can simplify access by
abbreviating the call. This means that you can use the syntax ArrayProperty[Index]
as opposed to ArrayProperty.Items[Index].
Either way is appropriate, and there is no right or wrong, however here is what I
think. The advantage to using the abbreviated version make repeated calls easier
to look at, especially if there are in one parameter list. The only disadvantage I
can think of is that someone else reading the code might not be able to determine
what you are referencing without some thought, or knowledge of the class in
Here's an example using a TStringList:
4 for I := 0 to MyStringList.Count - 1 do
9 for I := 0 to MyStringList.Count - 1 do
Again, in that example it really doesn't save much, but in my code I have some
classes I created and have to repeatedly call different sometimes. Here's an
example of something I might do, and how the abbreviation cleans things up:
12 for I := 0 to UserList.Count - 1 do
13 if AUser.read(UserList.Items[I].Company, UserList.Items[I].User) then
15 ACompanyStr := UserList.Items[I].Company;
16 AUserStr := UserList.Items[I].User;
Now the code in this example is pretty useless, and some would say why not use a
'with UserList.Items[I] do' statement to clean things up. However often I might
have these nested within other 'with' statments, so the 'with' solution is not
Now look at the abbreviated code:
18 for I := 0 to UserList.Count - 1 do
19 if AUser.read(UserList[I].Company, UserList[I].User) then
21 ACompanyStr := UserList[I].Company;
22 AUserStr := UserList[I].User;
It definetly reduces the amount of code, and I believe it does clean up the
What makes this all possible is the use of the 'default' directive with the
corresponding array property.
This can be used for many different items in delphi already including TStringList,
TListItem, etc. but there are some items that do not have default array properties
and therefore you cannot access in the abbreviated fashion.
If you attempt to access something that does not have the default array property, such as the TListView component (I.E. ListView[I].Caption instead of ListView.Items[I].Caption), you will recieve an error such as "Class does not have default property".