Dim i As String = "10.56"
Dim j As String
j = DirectCast(i, String)
Console.WriteLine(j)
OUTPUT- 10.56
I want to ask that i have used directcast in Right way. This ques tion is asked to me in interview. We can simply assign the value of i to j. Wats the use of then DirectCast Operator.
Um...I don't think you've quite got the essence of directcast. Directcast would be used to state that the value of the object is of the type you specify.
In the example you've given the variable i is already set as type string, so using direct cast to assign it to j doesn't really have any effect. DirectCast is generally used for specifying types of otherwise unidentifiable objects rather than for type conversion as described in a lot of documentation - for instance:
Dim o As Object = 5.213
Now, we reference object o after the fact. What type of data is in o (without looking back to where we assigned the value)? It's type "object", so who knows what is in there - it really could be any type, it could be single, double, string etc.
So we have another variable we wish to use the data from this variable o.
Dim MySingle As Single = DirectCast(o, single)
Dim MyDouble As Double = DirectCast(o, double)
Dim MyString As String = DirectCast(o, string)
So we are really telling the system that the value stored in object in its literal format is of the type we specified - in the first line, we are saying: "The type of data held in object o is of type single, assign this value to the variable MySingle"
If we tried:
Dim MyInteger As Integer = DirectCast(o, integer)
This would fail - because 5.213 is not an integer, it's a floating point numeric.
However, in this case, the CType method would work because we're taking the value from object and telling the system to convert the value held in object o to an integer rather than just saying "I want to view the value in object o and the value in object o is of type integer" - in which case, your application is going to complain "you're obviously on crack, 5.213 is not an integer in any world of math I'm familiar with".
however the following succeeds:
Dim MyInteger As Integer = CType(o, integer)
Why? Well CType isn't saying the same thing as DirectCast - CType is saying I want to view the value in object o and whatever value you have in object o, convert it to its integer representation.
So MyInteger now holds value 5.
Make sense?