Tuesday, July 08, 2008

"Foreach" loop in Delphi

Source : http://delphi.about.com/b/2004/08/13/delphi-9-teaser-foreach-loop.htm

Great stuff coming in the new release of Delphi. According to Danny Thorpe (Borland chief scientist) in the next release of Delphi, the compiler will support a new kind of for loop, the "for..in" loop. This *extended* version of the for loop repeats a group of embedded statements for each element in an array or an object collection. Sound like a foreach loop in C#? Even better!


Here's the syntax:

for <variable> in <container expression> do <statement>;

A "for..in" loop works just like a regular Delphi for loop, except that you do not have to pre-define a loop index variable.

Here's an example:

type
  TdotNetLang = (Delphi, CSharp, VBNet);
  TdotNetLangs = set of TdotNetLang;
procedure ForLoopTest(const NetLanguage: TTdotNetLangs);
var L: TdotNetLang;
begin
for L in NetLanguage do
// do something with L
end;

The new Delphi for..in syntax will support data types that the Delphi compiler knows contain multiple elements of a uniform data type: arrays (of elements), strings (of char), and even sets (of enums).


0 Comments: