What is the difference between the ctype function and the directcast function?

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.