Hallvard has a very nice post detailing the internal of enumerators (that is, Delphi new for..in loop). For example I realized that in my book I failed to mention you can use records to implement enumerators rather than classes, producing (slightly) more efficient code.

What I haven't seen mentioned anywhere, including the VCL source code, is how to hide the enumerator class from the external. All of the VCL classes with an enumerator add the enumerator class to the interface of the unit, as the main class (the one you want to enumerate) needs a GetEnumerator function returning the enumerator class. Now it is little know that you can implement this enumerator class as a private nested type, hiding it to any outside code. In fact, if the enumerator class is public, you could in theory allocate objects for it. If it is implemented as a private nested type, it is totally invisible... although it can be used by the calling code within its for..in loop.

To edit Hallvard initial code, you could write:

      type
      
TMyList = class(TList)
private
type
TMyListEnumerator = class
...
public
constructor Create(AMyList: TMyList);
function MoveNext: Boolean;
function GetCurrent: TMyObject;
property Current: TMyObject read GetCurrent;
end;
public
procedure Add(AMyObject: TMyObject);
function GetEnumerator: TMyListEnumerator;
end;

Of course, you can certainly write the same "nested type" code also when using records...