How to use the ToString method in VB?
In VB, the ToString method is used to convert an object into its equivalent string representation. There are several ways to use the ToString method.
- For primitive data types such as integers, floating point numbers, and booleans, you can directly use the ToString method to convert them to a string. For example:
Dim num As Integer = 10
Dim str As String = num.ToString()
- For custom class objects, you can override the ToString method in the class definition to provide a custom string representation of the object. For example:
Class Person
Public Name As String
Public Age As Integer
Public Overrides Function ToString() As String
Return "Name: " & Name & ", Age: " & Age.ToString()
End Function
End Class
Dim p As New Person()
p.Name = "John"
p.Age = 25
Dim str As String = p.ToString()
- For an array object, you can use the String.Join method to concatenate the elements of the array into a single string, and then call the ToString method to convert it to a string. For example:
Dim arr As Integer() = {1, 2, 3, 4, 5}
Dim str As String = String.Join(", ", arr)
str = str.ToString()
The above is the basic usage of the ToString method, which can be adjusted and expanded accordingly based on different data types and needs.