The command var = CType("123", Integer)
attempts to convert "123" even though it??™s a string, and this statement succeeds because VB will
implicitly cast "123" to an Integer. But the command var = DirectCast("123", Integer) will fail
because the compiler won??™t try any implicit conversions and attempts to directly convert a string
to an Integer. It??™s recommended to use DirectCast when you know a reference type conversion
will work and you need the extra performance benefit. Another difference between CType and
DirectCast is that you can only use DirectCast on types that have an inheritance relationship.
Therefore, you can??™t use DirectCast on value types, including structures.
The TryCast function has the same syntax as DirectCast and performs the same reference
type conversion. However, if the cast fails, the function returns Nothing instead of throwing an
error. So instead of handling errors from CType or DirectCast, you can use TryCast and check
for Nothing. In this code snippet, TryCast attempts to convert reference type x to a type of
EntryPoint. This conversion would normally cause an exception, but with TryCast, you simply
check for the result of the conversion:
Dim y As Object = TryCast(x, EntryPoint)
If y Is Nothing Then
'Do something here, for failed cast
Else
'Do something here, for successful cast
End If
Boxing
Another common type of conversion is a boxing conversion.
Pages:
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72