CType - VB.Net

If this conversion is not possible then an exception is thrown.
When you use Option Strict On any data type conversions must be explicit.

Dim iNumber As Integer = CType(12.5, Integer) 
Dim iNumber As Integer = CType("12.5", Integer)

The second argument is the name of the target class and is not enclosed in quotes.
Can be used on any valid expression.
If the argument cannot be cast directly to the target type in the case of the above conversion from a double to an integer.
CType will attempt to convert it even if it means losing the fractional part of the number.


If the argument cannot be converted to the target type in the case of a string to a number.

Dim iNumber As Integer = CType("sometext", Integer) 

Then the CType operator will throw an InvalidCastException error.


This is compiled inline, which means that the conversion code is part of the evaluation.
In somes cases there is no call to something else for evaluation, which makes execution faster.
If a narrowing conversion fails an OverflowException error is generated.




Never declare a new object when it is declared, (eg Dim object as New Connection). Always declare the object and then set the object before you actually need it and always remember to set it to NOTHING (eg set object = Nothing) when you have finished with it.


When using the IsMissing function the variable must always be declared as variant.


If you have any problems with the Int() or Cint() type conversion functions then use the Str() function to return a string representation of the number first, before converting.




© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext