Generating iterators

 

Introduction

Iterators are a new functionality in C# 2.0.  An iterator is a method, accessor or get operator, used to handle foreach iteration in a class or struct, without having to implement the entire IEnumerable interface.  Instead, you simply have to provide an iterator, which will simply browse your class' data structures.

 

 

Generating an iterator

Although an iterator can easily be modeled in the explorer, Objecteering can simplify this often repetitive task for data structures (attributes and associations).

 

To automatically generate an iterator, simply check the "Iterator" tickbox in the "Properties" tab of the auxiliary window for an attribute or an association (as shown in the screenshot below).

 

The "Properties" tab in the auxiliary window on an attribute or an association

 

After checking the "Iterator" tickbox, the iterator creation window shown below appears.

 

The "C# iterator definition" window

 

Key:

1.      If this field is left undefined, then the generated iterator will implement the "GetEnumerator" method.  If the field is defined, then a named iterator will be created.

2.      This field indicates that the IEnumerator<T> or IEnumerable<T> generic interface is to be implemented (adds a template parameter).

3.      This tickbox, which is checked by default, indicates whether or not personalized code can be entered for the loop browse.

4.      Entry zone used to iterate on non-trivial data structures (by default, the generated code is a simple date browse using the foreach instruction).

 

 

Note 1:  If you modify the properties of your attributes/associations, the iterator's code is not updated!

 

Note 2:  This functionality does not produce an accessor or a get operator.

 

 

The following table shows an example of a model containing an iterator and the code generated for it by Objecteering.

 

UML Model

Generated C#