Thursday, January 28, 2010

Difference between DirectCast and CType


The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type and DirectCast requires that the run-time type of an object variable to be the same as the specified type that it's being cast to.


The first thing to understand is that CType and DirectCast are not the same thing. Only CType can convert the underlying object to a new instance of an object of a different type. For example, if you want to turn an integer into a string. Since an Integer doesn't inherit a String, a new instance of a String object must be created in order to store the number as a String. CType can do this, DirectCast cannot. Note: There are other ways to do this too such as the
Convert.ToString method or CStr().


Dim MyInt As Integer = 123
Dim MyString1 As String = CType(MyInt, String)
Dim MyString2 As String = DirectCast(MyInt, String) ' This will not work


What DirectCast and CType do have in common is their ability to convert an object to a new type based on inheritance or implementation.

For example, if you have a String but it is stored in a variable of type Object, you can use DirectCast or CType to treat that variable as an object of type String because type String inherits type Object. In this case, the underlying data in memory is not actually changing, nor is any processing happening on that data.

Dim MyObject As Object = "Hello World"
Dim MyString1 As String = CType(MyObject, String)
Dim MyString2 As String = DirectCast(MyObject, String) ' This will work,since string is inherited from object


No comments:

Post a Comment