Cast or convert?


We've just turned Option Strict on in our project and I'm just cleaning up a few of the errors.

I've always used CType for all my conversions but my collegue said to use Convert.To.. Is there a particular reason to use one or the other

And along those lines when creating variables should one use Integer or Int32  Convert.To doesn't contain a ToInteger but CType does and I like to keep my code consistant.

Thanks

Morkai


Answer this question

Cast or convert?

  • Martijn_Bakker

    Well, first off Int32 and Integer are the same thing (so is int in C#).

    As for Convert.Toxxx, only use that when you actually need to convert something from one type to another.

    If all you're doing is casting, it's best to use DirectCast, which works the same as CType.

    In C# it's a bit simpler as CType and DirectCast are the same thing.

  • Nick Hertl - MSFT

    >Well, first off Int32 and Integer are the same thing (so is int in C#). 

    Okay cool, wasn't sure if there was some underlying difference

    >As for Convert.Toxxx, only use that when you actually need to convert 
    >something from one type to another. 

    I guess this beggars the question what is the actual difference between casting something and converting it

    According to helpfiles the CType function "Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface" which makes it sound like CType is just doing a Convert.Toxxx in the background.

    >If all you're doing is casting, it's best to use DirectCast, which works the same as CType.

    Noted, I see it has more error checking built in.

    Thanks

    Morkai

     

  • uranus65

    Just one point: DirectCast doesn't "work the same as CType". CType performs conversions, and works on value types. DirectCast only provides casting functionality, won't provide conversions, and works only on reference types. In theory, in cases in which you need only casting, DirectCast OUGHT to be more efficient than CType, but I've been unable to prove (in simple testing) that it actually is.
  • Cast or convert?