Type conversion is the process of changing a value from one type to another. For example, you can convert the string, "1234" to the number 1234. Data of any type can be converted to the String type. Some type conversions will never succeed because the types are too different.
Some types of conversions, such as from a string to a number, are time-consuming. The fewer conversions your program uses, the more efficient it will be.
In JScript .NET you can either have implicit or explicit conversion.
Explicit conversion is done by using the data type identifier (go to About Data Types for more information). To explicitly convert an expression to a particular data type, use the data type identifier followed by the expression to convert in parentheses. Explicit conversions require more typing than implicit conversions, but you can be more certain of the result.
Here is a small example showing first how the number 1234 (integer) can be converted to the string “1234” and then to a double.
var i : int = 1234; var d : double;
var s : String; s = String(i);
Now the variable s holds the string 1234. This type of conversion is called widening, since all possible integer values can be converted to string and string can also hold other values. Let us continue the example:
d = double(s);
Now the variable d holds the double 1234. This type of conversion is called narrowing since there are a lot of possible string values that cannot be converted to double (for example the string “Forsta”). Explicit narrowing conversions will usually work, but with loss of information. The string “Forsta” converted to a double will give NaN (not a number). But some types are incompatible and will throw an error, and for some values there is not sensible value to convert to.
Implicit conversion occurs automatically when values are assigned to variable of a certain type. The data type of the variable determines the target data type of the expression conversion.
Here is a similar example to the one above showing first how the number 1234 (integer) can be converted to the string “1234” and then to a double.
var i : int = 1234;
var d : double;
var s : String;s = i;
Now the variable s holds the string 1234. It was converted to string since the receiving variable where of type string. This is an example of widening implicit conversion. Let us continue the example:
d = s;Now the variable d holds the double 1234. This is an example of a narrowing conversion.
When this code is compiled, compile-time warnings may state that the narrowing conversions may fail or are slow. Implicit narrowing conversions may not work if the conversion requires a loss of information.