Anytype is great. It’s a primitive data type can use as a placeholder for any other data type, and comes in handy on many occasions. But don’t use it as a silver bullet, it might backfire.
Consider the next example.
static void AnyType_Test_1(Args _args)
{
utcDateTime dateTime;
AnyType value;
;
value = datetimeutil::utcNow();
dateTime = value;
info(strFmt("%1", dateTime));
}
{
utcDateTime dateTime;
AnyType value;
;
value = datetimeutil::utcNow();
dateTime = value;
info(strFmt("%1", dateTime));
}
We are assigning the current date and time to the AnyType variable, than back to a utcDateTime, and sending it to te screen. This neatly produces following output:
7/04/2009 19:27:15
Now consider the following example.
static void AnyType_Test_2(Args _args)
{
utcDateTime dateTime;
AnyType value;
;
value = "Here comes today's date";
value = datetimeutil::utcNow();
dateTime = value;
info(strFmt("%1", dateTime));
}
{
utcDateTime dateTime;
AnyType value;
;
value = "Here comes today's date";
value = datetimeutil::utcNow();
dateTime = value;
info(strFmt("%1", dateTime));
}
The anytype data types can be automatically converted to dates, enums, integers, reals, strings, guids, int64s, extended data types (records), classes, and containers by assigning a value to the type. […] However, after you have converted the anytype data type, you cannot then change it to another data type.
In the second example it failed to convert the utcDateTime because we assigned a string to the AnyType variable. This is fault very subtle, because no error or warning is shown when compiling such code, and can easily be overlooked.
Not only can (incorrect) use of AnyType cause faulty output, it can also trigger stack traces.
The following example is inspired by Greg.
The following example is inspired by Greg.
static void AnyType_Test_3(Args _args)
{
AnyType value;
;
value = NoYes::Yes;
value = datetimeutil::utcNow();
}
{
AnyType value;
;
value = NoYes::Yes;
value = datetimeutil::utcNow();
}
This will show the following error message and stack trace:
Error executing code: Wrong argument types in variable assignment.
It gets even nastier in the next example:
static void AnyType_Test_4(Args _args)
{
utcDateTime dt;
AnyType value = "string";
;
value = 3;
dt = value;
}
{
utcDateTime dt;
AnyType value = "string";
;
value = 3;
dt = value;
}
This will show you a message box saying:
Internal error number 25 in script.
Note: if you are looking to solve the error above (you can encounter it when trying to send an email from code), you can find the links to the hotfixes for ax 2009 here.
And also the error and stack trace we saw before:
Error executing code: Wrong argument types in variable assignment.
No comments:
Post a Comment