Method overloading

suggest change

Definition : When multiple methods with the same name are declared with different parameters, it is referred to as method overloading. Method overloading typically represents functions that are identical in their purpose but are written to accept different data types as their parameters.

Factors affecting

Return type alone does not select an overload. Consider a method named Area that performs a calculation, accepts various arguments, and returns the result.

Example

public string Area(int value1)
{
    return String.Format("Area of Square is {0}", value1 * value1);
}

This method accepts one argument and returns a string. If we call the method with an integer (say 5) the output will be "Area of Square is 25".

public  double Area(double value1, double value2)
{
    return value1 * value2;
}

Similarly if we pass two double values to this method the output will be the product of the two values, and the result is a double. This can be used for multiplication as well as for finding the area of a rectangle.

public double Area(double value1)
{
    return 3.14 * Math.Pow(value1,2);
}

This can be used especially for finding the area of a circle. It accepts a double value (radius) and returns another double.

Each of these methods can be called normally without conflict - the compiler will examine the parameters of each method call to determine which version of Area needs to be used.

string squareArea = Area(2);
double rectangleArea = Area(32.0, 17.5);
double circleArea = Area(5.0); // all of these are valid and will compile.

Note that return type alone cannot differentiate between two methods. For instance, if we had two definitions for Area that had the same parameters, like so:

public string Area(double width, double height) { ... }
public double Area(double width, double height) { ... }
// This will NOT compile.

If we need to have our class use the same method names that return different values, we can remove the issues of ambiguity by implementing an interface and explicitly defining its usage.

public interface IAreaCalculatorString {    
    string Area(double width, double height);
}

public class AreaCalculator : IAreaCalculatorString {
    string IAreaCalculatorString.Area(double width, double height) { ... } 
    // Explicit implementations have no access modifier. This one is used when the call
    // goes through IAreaCalculatorString, which removes the signature clash.
    public double Area(double width, double height) { ... }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents