How to convert one DataType to other using the CType Function?

Joined
Apr 14, 2008
Messages
6
Programming Experience
Beginner
need help from you..
this is my assignment and I dont know how to do this.....
How do I convert one DataType to other using the CType Function?
and can you show some examples......

really thanks for any reply......
 
Dim i As Integer
Dim str As String = "17"

i = CType(str, Integer)
'i now = 17

its strength, though, IMO, is converting between objects like

devMsg = CType(row.Cells(cDevMsg).FindControl("Label3"), Label).Text.Trim
 
There are also CObj, CByte, CShort, CInt, CLng, CDec, CSng, CDbl, CDate, CStr, CChar that work like CType. Those will attempt a wide variety of ways to convert the value to the desired type.

On the other hand, DirectCast will only work when you do explicit casts. It won't work to DirectCast the String "32" to an Integer because the value isn't really an integer. What you should use to parse the String into an Integer is Integer.Parse(). Then, you would say there is no reason to use DirectCast, but I would think it is more specific to the task you want to do. It shows you know what you variables will be at that point and you are not just trying a conversion to see if it works.

Also, CType does not exist in C# and other .NET languages. They are remnants of the older VB syntax. You will only find DirectCast in those other languages (not the keyword, but the functionality). The cast, the Integer.Parse and other similar conversion methods are actually implemented by the Framework while the CType and family and translated into common method calls by the VB compiler (like the handles keyword that creates a property at compile time).

Then, one could argue that in C# the explicit cast of a Double into an Integer does more than just change the reference's type, so I must admit it's more a matter of preference than anything else.
 
Back
Top