«^»
5.4. Instance methods

The ArrayList class provides a method called Add that can be used to add an object to the end of an ArrayList. Here it is in action:

0017:         tLanguages.Add("Visual_Basic")
0018:         tLanguages.Add("C#")
0019:         tLanguages.Add("Managed_C++")
0020:         tLanguages.Add("JScript")

These calls of Add are unlike the calls of Write, WriteLine, Readline and Parse. Because, here before the dot, we put the name of the object to which we want the Add method applied. We might have several ArrayList objects in our program: however, in these statements, we want the Add method applied to the tLanguages object.

This kind of method is called an instance method because the method is being applied to a specific instance of the type.

The call of an instance method has the form:

VariableName.MethodName(parameters)

Suppose in our program we include a method to output an ArrayList of Strings:

0029:     Sub OutputStringList(ByVal pArrayList As ArrayList)
0030:         For Each tString As String In pArrayList
0031:             Console.Write(tString & " ")
0032:         Next
0033:         Console.WriteLine()
0034:     End Sub

This method can then be called in the following way:

0021:         OutputStringList(tLanguages)

This produces the output:

Visual_Basic C# Managed_C++ JScript

The ArrayList class also provides a method for reversing the elements of an ArrayList. This is another instance method. Here is a use of it:

0022:         tLanguages.Reverse()

If we call OutputStringList again:

0023:         OutputStringList(tLanguages)

we will get the output:

JScript Managed_C++ C# Visual_Basic

The ArrayList class provides several other instance methods. Here is a use of Insert and Sort:

0024:         tLanguages.Insert(2, "J#")
0025:         OutputStringList(tLanguages)
0026:         tLanguages.Sort()
0027:         OutputStringList(tLanguages)

These statements produce the output:

JScript Managed_C++ J# C# Visual_Basic
C# J# JScript Managed_C++ Visual_Basic

All of these calls are calls of instance methods: a method is being applied to an instance of the class.