Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Method Overloading in C# (OOP’s) – Part 14

Posted by Ravi Varma Thumati on July 13, 2009

Method Overloading in C#

This technique permits multiple methods to be declared using the same name but with different parameters. Method overloading is our first look at polymorphism.

Method Overloading

One of the key features of object-oriented programming is polymorphism. Polymorphism permits objects to behave in different ways according to the manner in which they are used. One part of polymorphism is the ability for a method to behave differently according to the types and number of parameters that are passed to it. This is achieved through method overloading.

Method overloading allows the programmer to define many methods with the same name but with a different set of parameters. Each combination of parameter types is known as a signature of the method. When a call is made to one of these overloaded methods, the compiler automatically determines which of the methods should be used according to the arguments used in the call and the available method signatures.

One of the greatest advantages of method overloading is the improvement that it provides to code readability and maintainability. In languages that do not support this technique, or that of optional operands, a new method must be created for every possible combination of parameters. For example, in the ANSI C programming language to truncate a value you would use trunc, truncf or truncl according to the data type being rounded.

In C#, method overloading allows you to always call Math.Truncate. This becomes even more useful when a change in the requirements of the program means that data types change. Unlike with the older languages, the C# truncate method would require no code modification.

When using method overloading, each version of a method should perform the same general function using different data types or numbers of parameters. Although it is possible to create two methods with the same name that perform completely different tasks, this just reduces the quality of your code.

Creating an Overloaded Method

Creating an overloaded method is achieved by simply adding two or more methods of the same name to a class. The methods can be normal or static. As long as the method signatures differ, the code will compile correctly. In the following example, we will create a method that calculates the square of a number using different data types. To begin, create a new console application and add a new class file named “Calculate”. Add the following code to the new class:

class Calculate

{

public static int Square(int number)

{

Console.WriteLine(“Integer Square calculated”);

return number * number;

}

}

The new method calculates the square of an integer value. The Console.WriteLine command is included so that we can easily see the flow of execution. To test the calculation, modify the Main method of the program as follows and run the program to see the results.

static void Main(string[] args)

{

int squareMe = 5;

Console.WriteLine(Calculate.Square(squareMe));

}

/* OUTPUT

Integer Square calculated

25

*/

The program takes the integer value and squares it using the static Square method of the Calculate class, giving the correct result of twenty-five. However, if the data type of the value to be squared is changed, the result can be different. If you were to change the Main method so that the squared variable is a double the code will no longer compile because the double data type may not be implicitly cast to an integer.

static void Main(string[] args)

{

double squareMe = 5;                            // Does not compile

Console.WriteLine(Calculate.Square(squareMe));

}

In order to support the double data type we can add a second variation of the method to the Calculate class. This overloaded method will accept and return doubles rather than integers. Add the new method as follows:

public static double Square(double number)

{

Console.WriteLine(“Double Square calculated”);

return number * number;

}

Now that the Calculate class can square integers and doubles, change the Main method as follows and execute the program. You can see that the compiler correctly determines which of the overloaded methods to execute for each call to Calculate.Square.

static void Main(string[] args)

{

double squareMe = 5;

int squareMeToo = 5;

Console.WriteLine(Calculate.Square(squareMe));

Console.WriteLine(Calculate.Square(squareMeToo));

}

/* OUTPUT

Double Square calculated

25

Integer Square calculated

25

*/

Automatic Type Conversion

In the example above, a second variant of the method was created because we wanted to square a double and this could not be implicitly cast to an integer. However, where an implicit cast is possible, the compiler will perform this conversion automatically. In the following example, the Main method is updated to use a float. As you can see, because no overloaded method exists specifically for floats the double variation is used instead.

static void Main(string[] args)

{

float squareMe = 5;

Console.WriteLine(Calculate.Square(squareMe));

}

/* OUTPUT

Double Square calculated

25

*/

Return Type Limitations

The signature defines the name and the set of parameters for the method. In order to use overloaded methods, the signature must differ for each method declaration. This means that every overloaded method in a class must have either a different number of parameters or a different set of argument data types to every other method with the same name. However, the return type of the method is not included in this signature. This means that two methods that differ only in return type cannot be created in the same class. For this reason, the following code is invalid and so will not compile:

class Calculate

{

public static int Square(double number)

{

return (int)(number * number);

}

public static double Square(double number)

{

return number * number;

}

}

A Note on Reference Parameters

Where parameters are passed by reference, they are considered to be different to those passed by value. This means that it is valid to have an overloaded method with the same set of parameter data types if one version passes parameters by value and the other by reference.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: