Overloading Methods

C# enables you to define multiple methods with the same name in the same class, as long as those methods have different parameter lists. This is referred to as overloading the method name. See Listing 6-9 for an example.

Listing 6-9: Working with Overloaded Methods class Listing6 9 {

public static void Main() {

Listing6_9 MyObject;

MyObject = new Listing6 9(); MyObject.Add(3, 4); MyObject.Add(3.5, 4.75);

void Add(int Integer1, int Integer2) {

int Sum;

System.Console.WriteLine("adding two integers"); Sum = Integer1 + Integer2; System.Console.WriteLine(Sum);

void Add(double Double1, double Double2) {

double Sum;

System.Console.WriteLine("adding two doubles"); Sum = Double1 + Double2; System.Console.WriteLine(Sum);

Listing 6-9 implements two Add() methods. One of the Add() method takes two integers as input parameters, and the other takes two doubles as input parameters. Because the two implementations have different parameter lists, C# allows the two Add() methods to coexist in the same class. The Main() method calls the Add() method twice: once with two integer parameter values and once with two floating-point values.

As you can see in Figure 6-8, both methods run successfully, processing the correct data.

JJLnir [H dnEasvr√Č

Figure 6-8: The overloaded method adds integers and doubles.

When the C# compiler encounters a call to a method that has more than one implementation, it looks at the parameters used in the call and calls the method with the parameter list that best matches the parameters used in the call. Two integers are used in the first call to Add(). The C# compiler then matches this call up with the implementation of Add() that takes the two integer input parameters because the parameters in the call match the parameter list with the integers. Two doubles are used in the second call to Add(). The C# compiler then matches this call up with the implementation of Add() that takes the two double input parameters because the parameters in the call match the parameter list with the doubles.

Not all overloaded methods need to use the same number of parameters in their parameter lists, nor do all the parameters in the parameter list need to be of the same type. The only requirement that C# imposes is that the functions have different parameter lists. One version of an overloaded function can have one integer in its parameter list, and another version of the overloaded function can have a string, a long, and a character in its parameter list.

0 0

Post a comment