Overloading methods
You probably don't need an example, but rather a better understanding of what overloading is and what it brings to the table. The class constructor is a good example. Suppose I create a class that has a person's name and their address. Let's call the class clsBirthdayCards and it has the following members:
string name;
string addr;
string city;
string state;
int zip;
I wrote such an application once and most of the people that would be in the database would be from Indiana. Normally, I would create an instance of the class with:
clsBirthdayCards myCards = new clsBirthdayCards();
Notice that clsBirthdayCards() is the default constructor for this class. When called this way, the members of the class are initialized with default values (null for string, zero for the int). Visual Studio writes the necessary code for you...and doesn't even show it to you. However, because I knew that most of the people in the list would be from Indiana, I overloaded the constructor and wrote one that looked like:
public class clsBirthdayCards()
{
string name;
string addr;
string city;
string state;
int zip;
public clsBirthdayCards(string whichState)
{
state = whichState;
}
// Rest of class code
}
Now I have two class constructors, one that I can call with:
clsBirthdayCards myCards = new clsBirthdayCards();
and one I can call with:
clsBirthdayCards myCards = new clsBirthdayCards("Indiana");
Note that because the methods names are the same, the constructor is "overloaded" (i.e., there's more than one flavor of the constructor). The compiler knows which one to call based on whether there is an argument or not. The advantage is that I now have a class member named state that has a default value of "Indiana" assigned into it.
So when do you overload a method? For constructors, if you're not happy with the default values that would be assigned to the default constructor, overload it and pass in the values you want. For other methods, overloading is used when you want to use the same method name, but you need the functionality to be different in certain cases. Overloading requires that the method signatures be different.
Read the contructor overloading section, starting on p.235 over and over until you fully understand it.
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|