Pages

Monday, August 3, 2015

How to check if a Base Enum has a valid value

Base enums can use integer assignment to be set, but you can set it 0 to any positive valid integer up to 255 inclusive, and that does not mean it's a valid enum.

Take for example the base enum "ABC" (\Data Dictionary\Base Enums\ABC).  You can assign ABC=555, and it will store an integer value of 255 with no issue.

To check if an enum value is valid, you can use this method:

static boolean checkABCEnum(ABC _abc)
{
    return new DictEnum(enumNum(ABC)).value2Symbol(_abc));
}

Here is a sample job that will demonstrate how this can be an issue:

static void CheckIfEnumIsValid(Args _args)
{
    // Possible enum values 0, 1, 2, 3
    ABC         abcValid, abcInvalid;
        
    // Valid enum
    abcValid = ABC::C;
    info(strFmt("%1, %2", enum2int(abcValid), abcValid));
    
    // Invalid enum, but integer assignment works and is stored
    abcInvalid = 555;
    info(strFmt("%1, %2", enum2int(abcInvalid), abcInvalid));
    
    if(new DictEnum(enumNum(ABC)).value2Symbol(abcValid))
        info(strFmt("Enum with type %1 and integer value %2 (%3) is valid", typeOf(abcValid), enum2int(abcValid), abcValid));
    else
        error(strFmt("Enum with type %1 and value %2 is invalid", typeOf(abcValid), enum2int(abcValid)));
    
    if(new DictEnum(enumNum(ABC)).value2Symbol(abcInvalid))
        info(strFmt("Enum with type %1 and integer value %2 (%3) is valid", typeOf(abcInvalid), enum2int(abcInvalid), abcInvalid));
    else
        error(strFmt("Enum with type %1 and value %2 is invalid", typeOf(abcInvalid), enum2int(abcInvalid)));
    
    /*
        Output:
        3, C
        4, 
        Enum with type Enum and integer value 3 (C) is valid
        Enum with type Enum and value 4 is invalid
    */
}