I was just wondering why .Net provides two type conversion functionalities for us even though both are casting to targeted type. But now I could understand that they are different.
- CTypeCType is more flexible than DirectCast. Because CType can convert one type to another. For example Integer to String, String to Integer, Object to Integer etc... But there should be an implicit conversion available. For example,
Dim a As String = "2"
Dim b As Integer
b=a
This will work if the Option Strict is OFF. Because implicit casting functionality for converting string to integer is available in .Net. That's why we can use CType to cast from string to integer .
Example:
Dim t As String = "5"
Dim s As Integer = CType(t, Integer)
Now I would like to tell working of CType. CType will use vb run time routines for this. So this happens at run time. For instance i have to convert an integer to string. .Net will create a reference type variable for string. Then it will copy that integer to the new instance of string. Then it will return that string.
Here .Net uses run time resources. The integer is a value type. So Boxing is needed for converting to reference type(String). This will hit efficiency. - DirectCastExample:
Dim t As String = "5"
Dim w As Integer = DirectCast(t, Integer) This will not work
But,
Dim t As String = "5"
Dim w As String = DirectCast(t, String)
This will work. That means the type of source variable should be same as casting type at run time.
One more example:
Dim t As Object
t = 5
Dim w As Integer = DirectCast(t, Integer) This will work. But the following will not work. It will throw System.InvalidCastException
Dim t As Object
t = "5"
Dim w As Integer = DirectCast(t, Integer)
So we should know the type of the object at coding time.
DirectCast is faster than CType, because this is not using runtime VB helper functions. And there is no boxing, because DirectCast accepts only reference types as operands. - Is DirectCast more efficient than CType?Yes.
---- DirectCast is not using run time helper functions for conversion.
---- No boxing in DirectCast
---- So DirectCast is two times faster than CType.
But, there is a problem. The programmer need to ensure the run time type of the operand before using the DirectCast. If type may not match .Net will through Invalid cast exception. This is a big problem.