Thursday 19 July 2012

METHOD OVERLOADING


A lot of programming languages supports a technique called default/optional parameters. It allows the programmer to make one or several parameters optional, by giving them a default value. It's especially practical when adding functionality to existing code. For instance, you may wish to add functionality to an existing function, which requires one or more parameters to be added. By doing so, you would break existing code calling this function, since they would now not be passing the required amount of parameters. To work around this, you could define the newly added parameters as optional, and give them a default value that corresponds to how the code would work before adding the parameters.

As of writing this, C# does not support default parameters. They have been announced for C# version 4.0, but up until that, C# coders have been using a different technique, which basically does the same, called method overloading. It allows the programmer do define several methods with the same name, as long as they take a different set of parameters. When you use the classes of the .NET framework, you will soon realize that method overloading is used all over the place.

class SillyMath
{
    public static int Plus(int number1, int number2)
    {
        return Plus(number1, number2, 0);
    }

    public static int Plus(int number1, int number2, int number3)
    {
        return number1 + number2 + number3;
    }
}

We define a Plus method, in two different versions. The first one takes two paramaters, for adding two numbers, while the second version takes three numbers. The actual work is done in the version that takes three numbers - if we only wish to add two, we call the three parameter version, and simply use 0 as the third paramater, acting as a default value. I know, I know, it's a silly example, as indicated by the name of the class, but it should give you an idea about how it all works. Now, whenever you feel like doing advanced math by adding a total of four numbers (just kidding here), it's very simple to add a new overload:

class SillyMath
{
    public static int Plus(int number1, int number2)
    {
        return Plus(number1, number2, 0);
    }

    public static int Plus(int number1, int number2, int number3)
    {
        return Plus(number1, number2, number3, 0);
    }

    public static int Plus(int number1, int number2, int number3, int number4)
    {
        return number1 + number2 + number3 + number4;
    }
}

No comments:

Post a Comment