Monday, July 7, 2025

Packing Sets, Maps, Lists, etc. in D365FO: Why con2str can break your code

While working on what seemed like a routine task in Dynamics 365 Finance and Operations, I encountered an unexpected issue Specified cast is not valid when passing a Set as a parameter to a method. 


Here's what happened.

I had a simple and logical flow:

1. Pack a set or a list into a container with standard pack method.



2. Convert this container into a string with con2str global function.


3. Pass it to my function as an argument. (not depicted)

4. Convert this string back to a container via str2con.



5. Create a new set from the restored container via set create method.

Everything worked fine—until step 5.

Instead of a smooth reconstruction of the Set, I ran into an error. The root cause? The str2con() function. By default, str2con() interprets numeric values as Int64 (long integers). This silent type coercion corrupted the data structure expected by Set.create(), which led to the failure.


To avoid this issue altogether, do not use str2con() to restore containers that will be used for object reconstruction (like sets, maps, etc.). Instead, use:

  • con2base64str() to serialize the container

  • base64str2con() to safely deserialize it

These Global functions preserve the data types and internal structure of the container without any implicit type conversions.