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 if they have different names or different parameter lists, which means having different numbers or types of parameters. The following four lines of code show how you might distinguish methods by signature:

void MyMethod(int p1);
void MyMethod(int p1, int p2);    // different number
void MyMethod(int p1, string s1); // different types
void SomeMethod(int p1);          // different name

You can overload any method, not just constructors. The first three methods are all overloads of the MyMethod( ) method. The first method differs from the second and third in the number of parameters. The second method closely resembles the third version, but the second parameter in each is a different type. In the second method, the second parameter (p2) is an integer; in the third method, the second parameter (s1) is a string. These changes to the number or type of parameters are sufficient changes in the signature to allow the compiler to distinguish the methods.

The fourth method differs from the other three methods by having a different name. This is not method overloading, just different methods, but it illustrates that two methods can have the same number and type of parameters if they have different names. Thus, the fourth method and the first have the same parameter list, but their names are different.

A class can have any number of methods, as long as each one’s signature differs from that of all the others. Example 8-1 illustrates a new version of the Box class with two constructors: one that takes three integers and one that takes three integers and a string for the color.

Example 8-1. Overloading a method is a way to provide flexibility in the parameters that clients provide to your class methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_8_1_ _ _ _Overloading
{
    public class Box
    {
        // private variables
        private int length;
        private int width;
        private int height;
        private string color;

        // public methods
        public void DisplayBox( )
        {
            Console.WriteLine("Length: {0}, Width: {1}, Height: {2}
                         Color: {3}", length, width, height, color);
        }

        // constructor
        public Box(int theLength, int theWidth, int theHeight)
        {
            length = theLength;
            width = theWidth;
            height = theHeight;
            color = "brown";

        }

        public Box(int theLength, int theWidth, int theHeight,
                   string theColor)
        {
            length = theLength;
            width = theWidth;
            height = theHeight;
            color = theColor;
        }
    }

    public class Tester
    {
        static void Main( )
        {
            Box box1 = new Box(4, 8, 3);
            box1.DisplayBox( );
            Box blueBox = new Box(3, 5, 7, "blue");
            blueBox.DisplayBox( );
        }
    }
}

The output looks like this:

Length: 4, Width: 8, Height: 3 Color: brown
Length: 3, Width: 5, Height: 7 Color: blue

If a function’s signature consisted only of the function name, the compiler would not know which constructors to call when constructing the new Box objects, box1 and blueBox. However, because the signature includes the parameters and their types, the compiler is able to match the constructor call for blueBox with the constructor whose signature requires a string object:

Box blueBox = new Box(3, 5, 7, "blue");

public Box(int theLength, int theWidth, int theHeight, string theColor)

Likewise, the compiler is able to associate the box1 constructor call with the constructor whose signature specifies just three integer arguments:

Box box1 = new Box(4, 8, 3);

public Box(int theLength, int theWidth, int theHeight)

Notice that the constructor that doesn’t take a color automatically assigns a color of “brown” to all boxes created with that constructor. We changed the DisplayBox( ) method to output the color of the box, so you see that box1 is brown in the output.

Warning

When you overload a method, you must change the signature (the name, number, or type of the parameters). You are free, as well, to change the return type, but this is optional. Changing only the return type does not overload the method, and creating two methods with the same signature but differing return types generates a compile error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset