DirectCast vs CType

Dim Q As Object = 2.37
Dim I As Integer = CType(Q, Integer) Succeeds.
Dim J As Integer = DirectCast(Q, Integer) Fails.

The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType.
In the preceding example, the run-time type of Q is Double. CType succeeds because Double can be converted to Integer, but DirectCast fails because the run-time type of Q is not already Integer.

 

dicksonkho

 

One thought on “DirectCast vs CType

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.