Iterating Through Elements
- 2 minutes to read
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 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:
For example, the «ForEach(enumElement in clipType,template)», the template is executed for every element of the enumeration whose identifier is in the clipboard.
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.
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.
Below is an example of a template that creates an assignment statement for each public field in the class:
This template calls the #InitializeField# template for each field in the current class. The #InitializeField# template is shown below.
The initf template expands as follows. The private variable b is ignored.