Adding Methods

You can also add methods to your class to perform an operation on the data. If you want the method to be accessible from the instance of the class, you must declare the method as a public method; to make it accessible from instances of the class in the same assembly, declare it as Friend. Private methods are available only to other members within the class.

1. Add the method in Listing 3.6 to your Sentence class. This method calls the ToUpper method of a String, which is provided by the .NET Framework.

Listing 3.6. Creating a public method for a class

Public Sub UpperCase()

TextValue = TextValue.ToUpper() End Sub

2. Replace the code in the Startup event handler of ThisDocument with the code in Listing 3.7 so that the UpperCase method is called only on Sentence1.

Listing 3.7. Calling the UpperCase method of the Sentence class Dim Sentence1 as New Sentence()

Dim Sentence2 As New Sentence("This is my first sentence.") Sentence1.Text = "This is my first sentence. " Sentence1.UpperCase()

Me.Paragraphs(1).Range.InsertAfter( _ Sentence1.Text & Sentence2.Text)

3. Press F5 to run the solution.

When the solution runs, the code in Listing 3.6 passes text to the constructor for the second object, but it uses the default (parameterless) constructor for the first object and then reassigns a value to the Text property of Sentence1. After the call to the UpperCase method on the first object, the first sentence that is inserted into the document appears in uppercase, and the second sentence appears in sentence case, as shown in Figure 3.3.

THIS IS MY FIRST SENTENCE. This is my second sentence. |

Figure 3.3. Text inserted into the document using the Sentence class

0 0

Post a comment