Results 1 to 5 of 5

Thread: CType or DirectCast

  1. #1

    Thread Starter
    Registered User NicoNel2000's Avatar
    Join Date
    Feb 2004
    Location
    Beijing - China
    Posts
    296

    Resolved CType or DirectCast

    Which of the above is better to use, and why?

    Were just wondering....

    Cheers
    Last edited by NicoNel2000; Oct 28th, 2004 at 05:34 AM.

  2. #2
    PowerPoster
    Join Date
    Jul 2002
    Location
    Dublin, Ireland
    Posts
    2,148
    They perform different operations.

    DirectCast is faster because it just casts one object to a class - it doesn't try and do any conversion.

    CType looks for a type converter and uses that - so for example you can convert an Integer to a String because a converter exists.

  3. #3
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170
    The DirectCast keyword introduces a type conversion operation. You use it the same way you use the CType keyword, as the following example shows:

    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.

    Both keywords take an expression to be converted as the first argument, and the type to convert it to as the second argument. Both conversions fail if there is no conversion defined between the data type of the expression and the data type specified as the second argument.

    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.

    DirectCast throws an InvalidCastException error if the argument types do not match.
    So, use DirectCast when you can and if performance matters, else you're OK with CType.

  4. #4

    Thread Starter
    Registered User NicoNel2000's Avatar
    Join Date
    Feb 2004
    Location
    Beijing - China
    Posts
    296
    i see. Thanx mate

  5. #5
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Another difference is that DirectCast only works with reference types whereas CType works with both reference and value types.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width