Base of difference | DirectCast | CType |
Types | We generally used Directcast to cast reference types. | We generally used Ctype to cast value types. |
Portability | DirectCast is portable across many languages as it is not very specific to VB.NET. | On the other hand Ctype is specific to VB.NET and it is not portable. |
Performance | Performance of DirectCast is far better than ctype. | Performance wise ctype is slow when compared to DirectCast. |
Routines | As performance is better because no runtime helper routines of VB.NET are used for casting. | As we are aware performamce is slower this is because ctype casting requires execution of runtime helper routines of VB.NET. |
Exception | If we perform DirectCast on arguments if that don't match then it will throw InvalidCastException. | Here exceptions are not thrown while using ctype. |
Conversion | If we use DirectCast we cannot convert object of one type into another. Type of the object at runtime should be same as the type that is specified in DirectCast. Below is the example:-
Dim sampleNumber as Integer
Dim sampleString as String
sampleNumber=400
sampleString=DirectCast(sampleNumber,String)
Here above code will not work because runtime type of sampleNumber is Integer which is different from the specified type String. | In Ctype cast of object of one type into another if the conversion is valid. Below is the example:-
Dim sampleNumber as Integer
Dim sampleString as String
sampleNumber=400
sampleString=CType(sampleNumber,String)
This code is legal and the Integer 100 is now converted to a string. |