| CType and Directcast are same or different in csharp
Both of above are different and have many differences.
(1)CType can convert underlying object to a new instance of an object of a different type. To understand this we take a example to turn integer into a string. Since an integer cannot inherit a string, a new instance of a String object must be created in order to store the number as a string. This can be done by CType but not possible by DirectCast. We can also do this by Convert.ToString() method or by CStr().
Example:-
Dim MyIntVal As Integer = 123
Dim FirstString As String = CType(MyIntVal, String)
Dim SecondString As String = DirectCast(MyIntVal, String) ' Error will not work
(2)Both of these 2 have some common thing is that both have ability to convert an object to a new type based on inheritance or implementation. To understand this we take a example of we have string but it is stored in a variable of type Object. So we can use DirectCast or CType to convert this into string. To understand this we take below example.
Example:-
Dim MyStrObject As Object = "Hello World"
Dim MyFirstString As String = CType(MyStrObject, String)
Dim MySecondString As String = DirectCast(MyStrObject, String) ' This will work | | |