TwinCAT Engineering Notes
← All posts

Methods with optional arguments

Uses of method arguments with default values, their features and limitations in TwinCAT/CoDeSys.

TwinCAT 3.1.4026 introduced support for omitting method arguments when a default value is defined for the corresponding input parameter.

I’d like to show how this feature helps reduce boilerplate code and share a few interesting limitations I discovered while using it.

Overall, the feature works very well, with the exception of a few issues related to __TRY/__CATCH. As far as I know, these have already been fixed in newer TwinCAT versions. I reported them several times to Beckhoff support, and they confirmed they were working on a solution.

That said, there are still two areas that I believe could be improved.

1. Default values are not supported for ANY types

The compiler allows code such as:

targetString : ANY_STRING := SystemAnyTypeVariable

However, it generates a compilation warning indicating that this construct is not supported. As a result, every ANY argument still has to be supplied explicitly when calling the method, even when a default value would make perfect sense. That’s a missed opportunity.

2. Default values are not supported for VAR_IN_OUT CONSTANT

As a reminder, VAR_IN_OUT CONSTANT allows string literals to be passed by reference by creating an invisible temporary variable behind the scenes. It would be great if default values were supported here as well, but unfortunately they are not.

Where is this feature most useful?

There are many possible use cases, but my favorite one is cleaner string concatenation.

In my framework, I implemented a set of helper utilities that significantly simplify concatenation of both short strings (up to 255 characters) and long strings, for both STRING and WSTRING.

The screenshot below shows one possible implementation. If you adopt a similar approach in your own projects, you’ll probably feel like you’ve jumped from the programming capabilities of the 1980s into the 1990s. 🙂

String concatenation method

#TwinCAT #CoDeSys #PLC #IEC61131 #StructuredText #IndustrialAutomation