Overloading
Overloading is a great way to expose similar functionality in methods that all have the same name. The method signature, which is defined by the number, order, and type of parameters the method takes, determines which method is fired.You've used overloaded methods before, probably with something simple such as the ToString() method of many different classes. The Int32 structure, which is the structure that holds your integer values, has four overloads:
The framework knows which version of the method to call based on the parameters you provide. If you provide no parameters, the first one is called. If you pass in a string such as "C" (to format the number as currency), it knows to call the third version of the method.You can write your own overloaded methods as well. Going back to our car example, perhaps we want two Accelerate methods. In Listing 2.13, one method accelerates the car to a speed we give it, whereas the other method just provides momentary acceleration and doesn't need a parameter.
Int32.ToString();
Int32.ToString(IFormatProvider);
Int32.ToString(string);
Int32.ToString(string, IFormatProvider);
Listing 2.13. Overloaded methods in the Car class
C#
VB.NET
public class Car
{
public void Accelerate(int speed)
{
// code to make the car reach the value speed
}
public void Accelerate()
{
// code to make the car momentarily accelerate
}
}
Overloading makes your code a little easier to understand for others, especially if you're writing a class that will be used by other developers who won't see the compiled code. If you have three methods that essentially arrive at the same result with different parameters, there's less confusion if they're all named the same thing. Without overloading in the previous example, you might have methods like "AccelerateToASpeed" and "AccelerateMomentarily."
Public Class Car
Overloads Public Sub Accelerate(speed As Integer)
' code to make the car reach the value speed
End Sub
Overloads Public Sub Accelerate()
' code to make the car momentarily accelerate
End Sub
End Class