top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between directcast and ctype?

+2 votes
637 views

And which is used when?

posted Aug 25, 2014 by Muskan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

DirectCast

1.DirectCast is generally used to cast reference types.
2.When you perform DirectCast on arguments that don't match then it will throw InvalidCastException.
3.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.
4.To perform DirectCast between two different classes, the classes should have a relationship between them.
5.Performance of DirectCast is better than ctype. This is because no runtime helper routines of VB.NET are used for casting.
6.DirectCast is portable across many languages since it is not very specific to VB.NET

ctype

1.Ctype is generally used to cast value types.
2.Exceptions are not thrown while using ctype.
3.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.
4.To perform ctype between two different value types, no relationship between them is required. If the conversion is legal then it will be performed.
5.Performance wise, ctype is slow when compared to DirectCast. This is because ctype casting requires execution of runtime helper routines of VB.NET.
6.Ctype is specific to VB.NET and it is not portable.

answer Nov 28, 2014 by Manikandan J
...