Share via


Closer Look: Creating Multiple Versions of the Same Method with Overloading

In this lesson, you will learn how to add multiple versions of a method to your class.

In the previous lesson, you learned how to add methods to the Persons class. Sometimes there are cases where a single method will not do—for example, you might need to pass different data types to the method in different situations, or you might want to return different formats as a result.

You can create multiple versions of a method using a technique called overloading. When a class has more than one method with the same name but with a different set of arguments, the method is overloaded.

Overloading

To create an overloaded method, add two or more Sub or Function procedures to your class, each with the same name. In the procedure declarations, the set of arguments for each procedure must be different or an error will occur.

The following shows a method with two overloads, one which takes a String and the other which takes an Integer as an argument.

Public Sub TestFunction(ByVal input As String)
    MsgBox(input)
End Sub 
Public Sub TestFunction(ByVal input As Integer)
    MsgBox(CStr(input))
End Sub

If you were to call this method from your code and pass it a string, the first overload would be executed and a message box would display the string; if you passed it a number, the second overload would be executed, and the number would be converted to a string and then displayed in the message box.

You can create as many overloads as you need, and each overload can contain a different number of arguments.

In the Persons class, you will add a method with two overloads to return a person's middle initial: one with just the initial, the other with the initial followed by a period.

Try It!

To create an overloaded method

  1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson, Adding Methods to a Class, and complete the procedures.

  2. In Solution Explorer, select Persons.vb, and then on the View menu, choose Code.

  3. Add the following code below the existing methods.

    Public Function MiddleInitial() As String
        MiddleInitial = Left$(middleNameValue, 1)
    End Function 
    
    Public Function MiddleInitial(ByVal period As Boolean) As String
        MiddleInitial = Left$(middleNameValue, 1) & "." 
    End Function
    
  4. On the File menu, choose Save All to save your work.

Next Steps

In this lesson, you learned how to create an overloaded method. In the next lesson, you will learn how to add events to the class.

Next Lesson: Adding Events to a Class

See Also

Tasks

Adding Methods to a Class

Concepts

Considerations in Overloading Procedures

Other Resources

Programming with Objects: Using Classes

Visual Basic Guided Tour