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

Consider a method named Area that will perform calculation functions, which will accepts various arguments and return the result.

Example

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

This method will accepts one argument and return 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 are of type double. This can be used of multiplication as well as finding the Area of rectangles

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

This can be used specially for finding the area of circle, which will accepts a double value(radius) and return another double value as its Area.

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 {    
    public string Area(double width, double height);
}

public class AreaCalculator : IAreaCalculatorString {
    public string IAreaCalculatorString.Area(double width, double height) { ... } 
    // Note that the method call now explicitly says it will be used when called through
    // the IAreaCalculatorString interface, allowing us to resolve the ambiguity.
    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