DirectCast
|
ctype
|
DirectCast
is generally used to cast reference types. |
Ctype
is generally used to cast value types. |
When
you perform DirectCast on arguments that don't match then it will
throw InvalidCastException. |
Exceptions
are not thrown while using ctype. |
If you
use DirectCast, you 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. Consider the following example:
Dim sampleNum as Integer
Dim sampleString as String
sampleNum = 100
sampleString = DirectCast(sampleNum, String)
This code will not work because the runtime type of sampleNum is Integer,
which is different from the specified type String.
|
Ctype
can cast object of one type into another if the conversion is valid.
Consider the following example:
Dim sampleNum as Integer
Dim sampleString as String
sampleNum = 100
sampleString = CType(sampleNum, String)
This code is legal and the Integer 100 is now converted to a string.
|
To perform
DirectCast between two different classes, the classes should have
a relationship between them. |
To perform
ctype between two different value types, no relationship between them
is required. If the conversion is legal then it will be performed. |
Performance
of DirectCast is better than ctype. This is because no runtime helper
routines of VB.NET are used for casting. |
Performance
wise, ctype is slow when compared to DirectCast. This is because ctype
casting requires execution of runtime helper routines of VB.NET. |
DirectCast
is portable across many languages since it is not very specific to
VB.NET |
Ctype
is specific to VB.NET and it is not portable. |