C# v2.0 Iterators and the Visitor design pattern - 04-30-2005 , 05:16 PM
I've been playing with C# v2.0 today, and having quite a bit of fun. The
new version has added iterators. The iterators are coded directly into
the class to be iterated. For example:
public IEnumerable<int> Visit(SomeVisitor visitor)
int position = 0;
for(int i = 0; i < Count; i++)
yield return position;
This can then be used in a foreach construct:
foreach(int position in someObject.Visit(this))
// Do something with position here.
Where 'someObject' is the object to traverse, the class of which
contains the iterator code above, and 'this' is an instance of a class
derived from 'SomeVisitor.'
So as the object is traversed, the iterator first returns the position
information. Here it is just a simple integer, but it could be anything,
something much more complex, perhaps. Then the Accept method is called.
The idea is that you can traverse a collection where the Visitor design
pattern is used without having to explicitely call the Accept method;
the iterator takes care of that for you. Plus, you get additional
information about the traversal that can be used as well. Care would
have to be taken so that you know which comes first, the value returned
from the iterator or the Accept method being called. But it seems worth
This can be coded in different ways in other languages to the same
effect, but I thought this use of C# v2.0 iterators together with the
Visitor pattern was kinda neat.
Re: C# v2.0 Iterators and the Visitor design pattern - 04-30-2005 , 07:30 PM
You might also be interested in using iterators to explore graphs in various
traversal patterns (depth first, breadth first, etc). I have coded examples
"Wavemaker" <jabberdabber (AT) BiteMeHotmail (DOT) com> wrote
Re: C# v2.0 Iterators and the Visitor design pattern - 04-30-2005 , 08:09 PM
Thanks! Extremely useful...
see also Jerome Laban's Reflective Visitor
aq (AT) okaq (DOT) com
"Fred Mellender" <nospamPlease_fredm (AT) frontiernet (DOT) net> wrote
|Thread Tools||Search this Thread|