Fabulous Adventures In Coding
Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric.
Before I get going, a couple notable milestones.
First, this is post number 200! Who would have believed that I'd have so much to ramble on about? ("Anyone who knows you" would be the correct answer to that rhetorical question I suppose.)
Second, as of Sunday I am now over (cue Dr. Evil) one billion seconds old. Happy gigasecond to me, happy gigasecond to me…
OK, enough frivolity. Back to boring facts about JScript .NET's coercibility algorithm.
Today I'll finish up and give a more precise definition of how JScript .NET determines whether a particular value is coercible to a given type. Then we'll get back into lighter topics.
Suppose we have a value V which we wish to coerce to type T without data loss or error. For clarity I'll split the algorithm up into two sections, one for "special" types like classes, arrays and enumerations, and one for "primitive value" types like integers and strings.
Suppose T is a reference, enumerated, array, etc, type:
Now let's consider the primitive type coercion rules.
JScript .NET supports several numeric types: 8, 16, 32 and 64 bit integers in both signed and unsigned flavours, 32 and 64 bit floats and a decimal type. JScript .NET also supports a "char" type which is an unsigned 16 bit integer that holds a single Unicode UTF-16 value. JScript .NET also supports a scalar Date/Time type which is treated the same as a signed 64 bit integer unless otherwise noted.
Note that data loss is allowed when coercing anything to Boolean and when coercing strings to numbers.
If none of the above apply, V is not coercible to T, and will likely cause a type mismatch exception.