Difference between revisions of "CType"

From Xojo Documentation

(Sample Code)
 
Line 47: Line 47:
 
The following compares implicit and explicit type conversion:
 
The following compares implicit and explicit type conversion:
 
<rbcode>
 
<rbcode>
Dim s As Single
+
Var s As Single
Dim i As Integer
+
Var i As Integer
  
 
i = 5
 
i = 5
Line 57: Line 57:
 
The following illustrates loss of information in the conversion:
 
The following illustrates loss of information in the conversion:
 
<rbcode>
 
<rbcode>
Dim d As Double
+
Var d As Double
Dim i As Integer
+
Var i As Integer
  
 
d = 566.75
 
d = 566.75
Line 70: Line 70:
 
// 0 converts to False
 
// 0 converts to False
 
// non-zero converts to True
 
// non-zero converts to True
Dim i As Integer = 42
+
Var i As Integer = 42
  
Dim b As Boolean
+
Var b As Boolean
 
b = CType(i, Boolean)
 
b = CType(i, Boolean)
 
</rbcode>
 
</rbcode>

Latest revision as of 22:07, 16 July 2019

Language Keyword

Performs explicit type conversion (only for data types that can be implicitly converted).

Usage

result = CType (value, datatype)

Name Type Description
result Any The passed Value converted to the datatype.
value Any The value to be converted to datatype. This must be a value that can be implicitly converted to datatype.
datatype DataType A built-in datatype. This must be a datatype to which value can be implicitly converted.

Notes

The CType operator is the explicit version of type conversion. Implicit conversion is available via the assignment (=) operator.

CType does not necessarily preserve the value across the types. It converts the passed value source type to the destination data type. In that regard, it is identical to implicit conversion. If you are using CType to convert a real number data type (e.g., single, double, currency) to an integer data type, it truncates the value rather than rounds. Sign extension is preserved when converting from a signed data type to another signed data type. Conversion between signed and unsigned types (either way) preserves the bits but not the value.

Sample Code

The following compares implicit and explicit type conversion:

Var s As Single
Var i As Integer

i = 5
s = i // implicit conversion
s = CType(i, Single) // explicit conversion

The following illustrates loss of information in the conversion:

Var d As Double
Var i As Integer

d = 566.75
i = CType(d, Integer) // i = 566
i = d // i = 567

Convert an Integer to Boolean:

// Convert Integer to Boolean
// 0 converts to False
// non-zero converts to True
Var i As Integer = 42

Var b As Boolean
b = CType(i, Boolean)

See Also

= operator.