Pages

Sunday, 14 June 2015

Method Overloading

Method Overloading

Let's review our prior code
public int power(int x)         //declare method, x is formal parameter
{
 return x * x;
}
In the real world, we have float type variable. We can not pass float variables to power method.

C# support a class to have more than one method with the same name. This is called method overloading. Each method with the same name must have a different signature than the others.
  • The signature of a method consists of the following information from the method header of the method declaration:
    • The name of the method
    • The number of parameters
    • The data types and order of the parameters
    • The parameter modifiers
  • The return type is not part of the signature—although it’s a common mistake to believe that it is.
  • Notice that the names of the formal parameters are not part of the signature.
Following code is the example:
public int power(int x)          //power has int return type and int parameter
{
 return x * x;
}

public float power(float x)         //overloading power method, float as return type and parameter
{
 return x * x;
}
....
static void Main(string[] args)
{
 intCalculator myCalcultor = new intCalculator();

 int myInt = 3;
 Console.WriteLine("power(myInt)", myCalcultor.power(myInt));

 float myFloat = 3.3F;
 Console.WriteLine("power(myFloat)", myCalcultor.power(myFloat));
}
As you see, now power can take both int and float as parameter.

Just like method, constructor also can be overloaded.
You can overload contructor with the same way you overload a mthod.

0 comments:

Post a Comment