Changing data structure types in a C# scripted rule

If two or more subtypes of an object in your script include fields with the same name but different structures, automatic type selection may not work as required.

In order to identify the correct field, use the following methods:

  • Is to determine if your object is a specific type.

    Format as follows:

    <your object name>.Is<your object’s subtype name>()

  • As to indicate which subtype you want the rule to access.

    Format as follows:

    <your object name>.As<your object’s subtype name>()

Sample Scenario

You have an object called Order and would like to access its Items property in a C# rule, as in Order.Items. However, the object Order may have multiple types. For example:

  • LightweightOrder where Items is just a list of string values.
  • DetailedOrder where Items is a list of detailed complex objects describing each item of an order.

Problem: How can I determine which order type the object is?

Solution: Call Order.IsDetailedOrder(). A response of 'true' indicates the object is the DetailedOrder type.

Problem: When accessing items of an order such as Order.Items.s[1], the C# rule complains that Items is not a list of string values.

Solution: This is because by default, the C# rule tries to access the Order object as it was of the DetailedOrder subtype. You need to first test what type the Order is, and if it is LightweightOrder, tell the rule to access it as such, as follows:

If(Order.IsLightweightOrder()) {
string secondItem = Order.AsLightweightOrder().Items.s[1]; 
}

Problem: My request has the Order object populated with DetailedOrder data but I need to generate it as just the LightweightOrder. How can I change the type of order from DetailedOrder to LightweightOrder?

Solution: You can use Order = new LightweightOrder(). Note that you need to create the internal properties of this object before you use them. For example;

Order.Items = new ItemsStringArray()

Tip: Use the Insert Path functionality to generate a code snippet to get to any field of data model you need to use within your scripts. For details, see Create a Scripted Rule.

Back to top