Strings Are Objects

In Visual Basic 2005, a String is an object that has its own members, which you can use to manipulate the String. For example, if you start typing the code in Listing 4.10, when you type the period after AuthorName, IntelliSense displays all the methods and properties available for a String, as shown in Figure 4.3.

Listing 4.10. Methods for a String

Dim AuthorName As String = "Kathleen McGrath" Dim Names() As String = AuthorName.Split(" ") MsgBox("First Name: " & Names(0) & vbCrLf & _ "Last Name: " & Names(1))

You can convert data types to strings using the CStr function, but many types can be converted to a String by using the ToString() method. For

Dim AuthorName As String = "Kathleen McGrath" Dim Names() As String = AuthorName. T

4 LastlndexOf

w

Length

^ Remove

^ Replace

¬ęSplit

StartsWith

=

Substring

ToCharArray

_

ToLower

ToString

V

Common | All

Figure 4.3. Calling the Split method on a Siring example, if you want to display an integer in a message box and you have Option Strict turned on, you must first convert the Integer to a String. Replace the code in the ThisDocument class of a Word document solution with the code in Listing 4.11, and then run the code.

Listing 4.11. Displaying an Integer in a message box

Option Strict On

Public Class ThisDocument

Private Sub ThisDocument_Startup(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Startup

Dim ParagraphCount As Integer = Me.Paragraphs.Count MsgBox(ParagraphCount)

End Sub

Private Sub ThisDocument_Shutdown(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Shutdown

End Sub

End Class

When you run the code in Listing 4.11, a build error occurs indicating that Option Strict On disallows implicit conversions from Integer to

String. You can do one of two things. The first is to turn off Option Strict. Keep in mind that in addition to ensuring that you explicitly convert numeric types and strings, Option Strict restricts data type conversion that could result in data loss and generates errors when objects are late bound. Turning Option Strict on can help reduce errors in your code.

The second option is to explicitly convert the Integer to a String. You do this by using the CStr function or by calling the ToString() method on the integer. Change the line of code that reads MsgBox (ParagraphCount) to MsgBox (ParagraphCount.ToString()), and press F5. This time the message box displays the total number of paragraphs in the document.

0 0

Post a comment