Article
Object Oriented C# for ASP.NET Developers
Overloaded Methods
Sometimes it makes sense to have two different versions of the same method. For example, when we modified the PickNut method in the CoconutTree class to require a parameter that specified the number of nuts to pick, we lost the convenience of being able to pick a single nut by just calling PickNut(). C# actually lets you declare both versions of the method side by side and determines which one to use by the number and type of the parameters passed when the method is called. Methods that are declared with more than one version like this are called overloaded methods.
Here's how to declare the two versions of the PickNut method:
public bool PickNut() {
if (numNuts == 0) return false;
numNuts = numNuts - 1;
return true;
}
public bool PickNut(int numToPick) {
if (numToPick < 0) return false;
if (numToPick > numNuts) return false;
numNuts = numNuts - numToPick;
return true;
}
One way to save yourself some typing is to notice that PickNut() is actually just a special case of PickNut(int numToPick); that is, calling PickNut() is the same as calling PickNut(1), so you can implement PickNut() by simply making the equivalent call:
public bool PickNut() {
return PickNut(1);
}
public bool PickNut(int numToPick) {
if (numToPick < 0) return false;
if (numToPick > numNuts) return false;
numNuts = numNuts - numToPick;
return true;
}
Not only does this save two lines of code, but if you ever change the way the PickNut method works, you only have to adjust one method instead of two!
Constructors can be overloaded in the same way as normal methods. If you miss the convenience of being able to create a new Tree of height zero, you can declare a second constructor that takes no parameters:
private int height;
public Tree() {
this(0);
}
public Tree(int height) {
if (height < 0) this.height = 0;
else this.height = height;
}
Note that we have once again saved ourselves some typing by implementing the simpler method (Tree()) by invoking a special case of the more complex method (Tree(0)). In the case of a constructor, however, you call it by the special name this.