Iterating Through Elements

This topic describes how to create a template that processes code elements such as class members, enumeration elements, etc. The CodeRush templates engine enables you to iterate through elements (for example, enumeration items), apply a template to each of them and concatenate the results.

The text command used for iteration is «ForEach(iteration_bounds,template)». This text command's parameters are detailed in the Iteration Bounds and Target Template sections.

Iteration Bounds

The iteration_bounds parameter is a string built according to the following syntax:

[visibility] item in scope

The iteration_bounds string elements can have the following values:

visibility (optional)

item

keyword

scope

  • private
  • protected
  • internal (Friend in VB)
  • protectedlntemal
  • public
  • abstract (Mustlnherit in VB)
  • element (Node in VB)
  • parameter
  • local
  • field
  • enumElement
  • member
  • method
  • property
  • event
  • class
  • struct
  • interface
  • enum
  • namespace
  • line (a line in a multi-line text)
  • in
  • block (current code block)
  • itemElement
  • method
  • property
  • this (Me in VB)
  • base (Inherited in VB, all ancestors of the active class)
  • clipClass (type name from the clipboard)
  • clipType (the identifier type from the clipboard)
  • clipboardText
  • file

For example, the «ForEach(enumElement in clipType,template)», the template is executed for every element of the enumeration whose identifier is in the clipboard.

Note

The template with the "enumElement in clipType" bounds should be expanded when the clipboard contains an enumeration name.

The "private member in this" is another example of the iteration_bounds value: the «ForEach» text command with such iteration_bounds iterate through every private member in the active class.

Target Template

You can specify the template applied to each iteration element using the template parameter. The target template can access two variables:

  • itemType — The type of the current iteration element (can be empty).
  • itemName — The current iteration element.

You can insert the values of these variables into your child template as described in the Using Variables article. Use the «?Get(itemType)» and «?Get(itemName)» text commands for this.

Example

Below is an example of a template that creates an assignment statement for each public field in the class:

Ext_Templates_Iterate1

This template calls the #InitializeField# template for each field in the current class. The #InitializeField# template is shown below.

Ext_Templates_Iterate2

The initf template expands as follows. The private variable b is ignored.

Ext_Templates_Iterate3_GIF

See Also