|
-
Oct 8th, 2006, 03:39 PM
#1
Thread Starter
Lively Member
[Resolved] Difference between convert.tostring and Ctype
Last edited by Xcoder; Oct 9th, 2006 at 08:55 AM.
Last edited by Xcoder : 09-10-2001 at 12:45 AM.
-
Oct 8th, 2006, 06:28 PM
#2
Re: Difference between convert.tostring and Ctype
Convert - Converts a base data type to another base data type
http://msdn2.microsoft.com/en-us/lib...m.convert.aspx
CType - Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.
http://msdn2.microsoft.com/en-us/library/4x2877xb.aspx
-
Oct 8th, 2006, 06:45 PM
#3
Re: Difference between convert.tostring and Ctype
ToString should used when you want to obtain a string representation of an object that is not a string, e.g. displaying a number in a TextBox:
VB Code:
Dim myNumber As Integer = 100
myTextBox.Text = myNumber.ToString()
CType, or the specialised versions CStr, CInt, CDbl, etc. should be used when you need to cast a reference to the specific type of the object. What I mean by that is that you should only use CType when the object itself is already that type, but it is being accessed via a reference of a different type, e.g. getting an item from an ArrayList:
VB Code:
Dim myCollection As New ArrayList
myCollection.Add("Hello World")
Dim myString As String = CType(myCollection(0), String)
In this case the object itself is already a String, but the ArrayList.Item property returns an Object reference, so you need to cast it as type String in order to treat it as a String. You can use CType, CStr, CInt, etc. to perform conversions in some instances but you shouldn't. You should use those operators only for casting. For instance, this is quite valid:
VB Code:
Dim myString As String = "100"
Dim myNumber As Integer = CType(myString, Integer)
but you should not do that. If the object itself is being changed from one type to another then you should use proper conversion functions, e.g.
VB Code:
Dim myString As String = "100"
Dim myNumber As Integer = Convert.ToInt32(myString)
Also, despite what some people would have you believe there is nothing wrong with using CStr, CInt, CDbl, etc. They are simply specialised versions of CType for each inbuilt VB data type. If you use Integer instead of Int32 then you should use CInt instead of CType(X, Integer) because they are equivalent.
-
Nov 14th, 2006, 01:11 AM
#4
Frenzied Member
Re: [Resolved] Difference between convert.tostring and Ctype
What is the internal difference between Convert.To... and Ctype? Thanks Again.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|