Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CType, DirectCast, Parse, Convert fundamentals

Status
Not open for further replies.

ashishraj14

Programmer
Mar 1, 2005
92
AU
What is the fundamental difference between CType, DirectCast, Parse, Convert different?

thanks
 
The following example should illustrate the difference between CType and DirectCast.

Code:
Dim a As Object
Dim b As Object
Dim i As Integer

a = 1 [COLOR=green]'the object [b]a[/b] contains an integer[/color]
b = "1" [COLOR=green]'the object [b]b[/b] contains a string[/color]

i = DirectCast(a, Integer) [COLOR=green]'Good: a contains an integer[/color]

i = DirectCast(b, Integer) [COLOR=green]'Bad: b contains a string[/color]

i = CType(b, Integer) [COLOR=green]'Good: CType [b]will[/b] convert a string to an integer[/color]

__________________________________________
Try forum1391 for lively discussions
 
Yes, the Help files state: "DirectCast requires the run-time type of an object variable to be the same as the specified type". So the string "b" in the above example is not the same type as an integer, therefore failing the DirectCast.
 
Both CAST and CONVERT are used in Transact-SQL (MS SQL) to explicitly convert an expression of one data type to another. CAST and CONVERT provide similar functionality.

But, CAST offers other edit-like features. Check the following link for examples:

PARSE, as in the DateTime.Parse Method, converts the specified string representation of a date and time to its DateTime equivalent.



__________________________________________
Try forum1391 for lively discussions
 
I add a little question

Difference between

Cstr(obj)
And
Ctype(obj ,String)

?

- - - - - - - - - - - - - - - - - -
Im three apples high, Im blue, and i most certainly like that cold beer that should be every mans right after a hard days work!
 
According to msdn:
microsoft said:
CType is compiled inline, meaning the conversion code is part of the code that evaluates the expression. Execution is faster because there is no call to a procedure to accomplish the conversion.

----------------------------------------------------------------------

Need help finding an answer?

Try the search facility ( or read FAQ222-2244 on how to get better results.
 
In addition to casting, CType will do a check for a valid destination data type; flagging Long to Integer, for example.

CInt, CStr and CBool will not check for valid data types.

__________________________________________
Try forum1391 for lively discussions
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top