Posts Tagged ‘Converting’

CType and DirectCast

Friday, July 3rd, 2009

VB.NET supports 2 different keywords which are related to casting.

DirectCast takes the object which is passed in and assumes it to be of the casted type or an inherited type.  This means that if you try to DirectCast an Integer to a Single, it won’t work.  If the compiler can see that it won’t work because it isn’t an inherited type, you’ll get a compiler error.  If you try it on a variable in eg. an Object at runtime, you’ll get an InvalidCastException.

The alternative is to use CType, which is much cleverer and will try to find a way to convert from one type to another.  This means that you can Ctype(“2.334″, Single) and it will parse the string and give you a Single length floating point number.  It will also check for overloading of the CType operator to see if it can convert using that.  This makes it very powerful, although it does come with the cost of a lot more processor usage.  However, for most modern applications, unless you are doing something heavily time constrained with a large amount of iterations in a  loop, it is unlikely to be an issue.