Overloading Methods and Constructors
Often, you'll want to have more than one function with the same name. The most common example of this is to have more than one constructor. In the examples shown so far, the constructor has taken a single parameter: a DateTime object. It would be convenient to be able to set new Time objects to an arbitrary time by passing in year, month, date, hour, minute, and second values. It would be even more convenient if some clients could use one constructor, and other clients could use the other constructor. Function overloading provides for these exact contingencies.
The signature of a method is defined by its name and its parameter list.. Parameter lists can differ by having different numbers or different types of parameters. For example, in the following code, the first method differs from the second in the number of parameters, and the second differs from the third in the types of parameters:
void myMethod(int p1); void myMethod(int p1, int p2); void myMethod(int p1, string s1);
A class can have any number of methods, as long as each one's signature differs from that of all the others.
Overloaded methods may have different return types, but changing only the return type does not change the signature, and thus is not sufficient to overload the method.
void myMethod(int p1); string myMethod(int p1, int p2); // legal void otherMethod(int p1); string otherMethod(int p1); // not legal
In the snippet shown here, myMethod is overloaded by changing the number ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access