Explicit Typing

Print Friendly, PDF & Email

◷ Reading Time: 2 minutes

When designing and modeling rules, you generally do not need to know about the types. However, there are scenarios in which you need to care about the types explicitly, especially when it comes to formulae and calculations.

Constants and Values

When assigning and using constants, types can be specified by using the suffix of the values. For example, 23i refers to an Integer value of 23. To learn more about the suffix, refer to here.

Variables and Parameters

If the value is stored in parameters, or they are provided as constants, you can use functions to explicitly define the result type of the calculation. Simply use the definition below and you can then use functions called int, long, double, and decimal to specify the type of the result from the evaluation process.

public static class ExplicitTypeFunctions
{
    /// <summary>
    /// Makes sure the value is converted to an integer
    /// </summary>
    /// <returns>Integer value</returns>
    [Function("int")]
    public static int ToInt(object value)
    {
        if (value == null)
            return 0;
 
        return (int)ConvertHelper.ChangeType(value, typeof(int));
    }
 
    /// <summary>
    /// Makes sure the value is converted to long
    /// </summary>
    /// <returns>Long value</returns>
    [Function("long")]
    public static long ToLong(object value)
    {
        if (value == null)
            return 0;
 
        return (long)ConvertHelper.ChangeType(value, typeof(long));
    }
 
    /// <summary>
    /// Makes sure the value is converted to long
    /// </summary>
    /// <returns>Decimal value</returns>
    [Function("decimal")]
    public static decimal ToDecimal(object value)
    {
        if (value == null)
            return 0;
 
        return (decimal)ConvertHelper.ChangeType(value, typeof(decimal));
    }
 
    /// <summary>
    /// Makes sure the value is converted to long
    /// </summary>
    /// <returns>Decimal value</returns>
    [Function("double")]
    public static double ToDouble(object value)
    {
        if (value == null)
            return 0;
 
        return (double)ConvertHelper.ChangeType(value, typeof(double));
    }
}

For example, with the number 23m you expect to return a decimal type, but applying functions explicitly changes/converts the types.

var vc = new VariableContainer();
vc.RegisterFunction(typeof(ExplicitTypeFunctions));
 
// Returns double
Assert.AreEqual(typeof(double), DynamicEvaluation.ExpressionEval.Default.Compute(vc, "double(23m)").GetType());
 
// Returns int
Assert.AreEqual(typeof(int), DynamicEvaluation.ExpressionEval.Default.Compute(vc, "int(23m)").GetType());

Feel free to change the functional implementation to suit your needs.

Updated on July 22, 2019

Was this article helpful?

Related Articles