Tuesday, March 16, 2010

Method Overloading

Overloading methods means that we can give the same name to more than one method and let the compiler load the appropriate method according to the number and type of parameters. It might be suitable to use method overloading if the purposes of the methods are similar. For example, if we would like to create one method to return the square root of an integer and another to return the square root of a real number, we would use the same name for both methods:
int  SquareIt(int x)
double SquareIt(double f)
Then if we use the following call:
SquareIt(3.25);
The compiler will invoke the method SquareIt(double f), which uses a real parameter.
When we use the following call:
SquareIt(44);
The compiler will invoke the method SquareIt(int x), which uses an integer parameter.
The return type does not have any effect on overloading. That means that methods might have similar names and return types, but the compiler can still differentiate between them as in the following example:
void SquareIt(int x)
void SquareIt(double f)
Note: - The binding between the specific method and the call is done at compile time, before the program runs. This is called static or early binding, as opposed to dynamic or late binding used with virtual methods.
It is also possible to overload methods that use the same type but a different number of parameters. For example:
void MyMethod(int m1) { }
void MyMethod(int m2, int m3) { }
One important use of overloading is operator overloading to invent new uses for operators.
In the following example, three methods use the name MyMethod, but each uses different parameters. The three methods are called from within the Main method and generate three different results.
Example 6-3
//Example 6-3.cs
//Overloading methods
using System;
class MyClass
{
    //Using a string parameter:
    static void MyMethod(string s1)
    {
        Console.WriteLine(s1);
    }
    //Using an integer parameter:
    static void MyMethod(int m1)
    {
        Console.WriteLine(m1);
    }
    //Using a double parameter:
    static void MyMethod(double d1)
    {
        Console.WriteLine(d1);
    }
    static void Main()
    {
        string s = “This is my string”;
        int m = 134;
        double d = 122.67;
   
        MyMethod(s);
        MyMethod(m);
        MyMethod(d);
    }
}

No comments:

Post a Comment