Delphi 2007 Handbook




Essential Pascal








October 18, 2007

Enumerators and Nested Types

Hallvard has a very nice post on the internals of enumerators, I wanted to chime in mentioning a slightly different coding style.

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...





 

1 Comments

Enumerators and Nested Types 

Actually, I discussed this very use of nested classes
two weeks ago in response to Nick Hodges' blog article
about nested classes...
 http://blogs.codegear.com/nickhodges/2007/10/03/38952

Michael
Comment by M J Marshall [http://www.kingstairs.com] on October 18, 07:57


Post Your Comment

Click here for posting your feedback to this blog.

There are currently 0 pending (unapproved) messages.