✏️ Explanatory Question

Create() and Pack() Method in Map in D365 F&O - X++ Code

👁 13 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Create() Method: Creates a map from the container that was obtained from a previous call to the Map.pack method.

Pack() Method: Serializes the current instance of the Map class.

Below runnable X++ job that demonstrates how to:

  1. Create a Map
  2. Insert values
  3. Pack the map into a container
  4. Unpack the container using Map::create()
  5. Display values from the restored map

static void Job_MapCreateFromContainerExample(Args _args)
{
    Map         originalMap, restoredMap;
    container   packedMap;
    str         key;
    int         value;

    // Step 1: Create a new Map with String keys and Integer values
    originalMap = new Map(Types::String, Types::Integer);

    // Step 2: Insert key-value pairs
    originalMap.insert("Apple", 10);
    originalMap.insert("Banana", 20);
    originalMap.insert("Cherry", 30);

    // Step 3: Pack the map into a container
    packedMap = originalMap.pack();

    // Step 4: Restore the map from the packed container
    restoredMap = Map::create(packedMap);

    // Step 5: Display the restored values
    key = "Apple";
    value = restoredMap.exists(key) ? restoredMap.lookup(key) : -1;
    info(strFmt("Key = %1, Value = %2", key, value));

    key = "Banana";
    value = restoredMap.exists(key) ? restoredMap.lookup(key) : -1;
    info(strFmt("Key = %1, Value = %2", key, value));

    key = "Cherry";
    value = restoredMap.exists(key) ? restoredMap.lookup(key) : -1;
    info(strFmt("Key = %1, Value = %2", key, value));
}

1. What is pack() and create()?

  • map.pack() turns the map into a container — like compressing a folder.

  • Map::create(container) unpacks that container — like unzipping the folder back into a map.