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.
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.
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.
To create an overloaded method
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.
In Solution Explorer, select Persons.vb, and then on the View menu, choose Code.
Add the following code below the existing methods.
On the File menu, choose Save All to save your work.
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