DirectcastKeyword introduces the type conversion operation. How to use this keyword andCtypeThe keywords are the same, as shown in the following figure:
Dim Q As Object = 2.37 ' Requires Option Strict to be Off.Dim I As Integer = CType(Q, Integer) ' Succeeds.Dim J As Integer = DirectCast(Q, Integer) ' Fails.
The expression to be converted between the two keywords is used as the first parameter, and the type to be converted is used as the second parameter. If the conversion between the data type of the undefined expression and the data type specified by the second parameter fails, both types of conversion will fail.
The difference between the two keywords is: as long as the effective conversion between expressions and types is defined,CtypeAndDirectcastThe runtime type of the object variable must be the same as the specified type. However, if the specified expression type and the runtime type are the sameDirectcastRuntime Performance RatioCtypeThe runtime performance is good.
In the preceding example,QThe runtime type of isDouble.CtypeBecauseDoubleCan be convertedIntegerAnd succeeded,DirectcastBecauseQThe runtime type of is notIntegerBut failed.
If the parameter type does not match,DirectcastWill causeInvalidcastexceptionError.