TwinCAT Engineering Notes
← All posts

Working with Variable-Length Collections in Structured Text Using IEnumerator

How to bypass the limitations of fixed-size arrays in TwinCAT and CoDeSys. Implementing the IEnumerator interface for flexible dynamic sequence iteration.

One of the limitations of Structured Text is the lack of proper support for variable-length collections. For example, imagine implementing a string Split function: • '12,34,56'['12', '34', '56']'12,34,56,78'['12', '34', '56', '78']

❌ The problem is that the compiler expects array sizes to be known at compile time.

💡 One possible solution is to return an IEnumerator instead of an array.

IEnumerator represents a sequence of data as an object with an internal cursor that can be traversed using a WHILE loop.

The interface is very simple: • ➡️ Property Current -> returns the current element in the sequence. Depending on the implementation, this could be a POINTER TO INT, POINTER TO STRING, POINTER TO __SYSTEM.AnyType, or, in OpenFramework, a REFERENCE TO GENERIC_VALUE. • ➡️ MoveNext() : BOOL -> moves the cursor to the next element and returns TRUE if such an element exists. • ➡️ Reset() -> returns the enumerator to its initial state.

⚠️ Important notes: • Before the first call to MoveNext(), the value of Current is undefined (null, zero). • After MoveNext() returns FALSE, the value of Current is also undefined.

🔄 Returning to our Split example: Instead of returning an array of unknown size, the function can return an IEnumerator that exposes all substrings one by one. Even better, we can implement a complementary Join function that accepts an IEnumerator as input. This allows both functions to work with collections of arbitrary size without relying on fixed-length arrays.

✅ In practice, IEnumerator provides a simple way to bring dynamic collection-like behavior to Structured Text while staying within the language’s constraints.

Examples of this approach can be found in the TwinCAT.OpenFramework.Test project by this link: TwinCAT.OpenFramework IEnumerator Examples

#TwinCAT #PLC #StructuredText #IndustrialAutomation #IEC61131 #SoftwareEngineering #OpenFramework