Overloading Methods

Often, you’ll want to have more than one method with the same name. The most common example of this is to have more than one constructor with the same name, which allows you to create the object with different types of parameters, or a different number of parameters. For example, if you were creating a Box object, you might have circumstances where you want to create the Box object by passing in the length, width, and height. Other times, you might want to create a Box object by passing in an existing Box object. Still other times, you might want to pass in just a length, without width and height. Overloading the constructor allows you to provide these various options.

Chapter 7 explained that your constructor is automatically invoked when your object is created. Let’s return to the Box class created in that chapter. The constructor in that chapter took three integers for length, width, and height. That works fine for most boxes, but suppose you have a situation where some of the boxes might need a color. That’s an entirely different parameter, and with a different data type, as well (a string, in this case). Some boxes might need a color; others might not. You can provide separate constructors for the colored and noncolored boxes.

To overload your constructor, you must make sure that each constructor has a unique signature. The signature of a method is composed of its name and its parameter list, but not its return type. Two methods differ in their signatures ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.