DirectCast is used to convert the type of an object that requires the run-time type to be the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and the type.
DirectCast
is twice as fast for value types (integers, etc.), but identical for reference types.
Dim MyInt As Integer = 123 Dim MyString1 As String = CType(MyInt, String)Dim MyString2 As String = DirectCast(MyInt, String) ' This will not work
Dim MyObject As Object = "Hello World"Dim MyString1 As String = CType(MyObject, String)Dim MyString2 As String = DirectCast(MyObject, String) ' This will work
A way to check in code if DirectCast will work is by using the TypeOf operator:If TypeOf MyObject Is String Then
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. |
No comments:
Post a Comment