HI WELCOME TO SIRIS

Making method parameters optional using method overloading in c#

Leave a Comment
we will discuss making method parameters optional using method overloading

This method allows us to add any number of integers
public static void AddNumbers(int firstNumber, int secondNumber, 
    int[] restOfNumbers)
{
    int result = firstNumber + secondNumber;
    if (restOfNumbers != null)
    {
        foreach(int i in restOfNumbers)
        {
            result += i;
        }
    }

    Console.WriteLine("Sum = " + result);
}



If we want to add 5 integers - 10, 20, 30, 40 and 50. We call the method as shown below.
AddNumbers(10, 20, new int[]{30, 40, 50});

At the moment all the 3 parameters are mandatory. If I want to add just 2 numbers, then I can invoke the method as shown below. Notice that, I am passing null as the argument for the 3rd parameter.
AddNumbers(10, 20, null);

We can make the 3rd parameter optional by overloading AddNumbers() function as shown below.
public static void AddNumbers(int firstNumber, int secondNumber)
{
    AddNumbers(firstNumber, secondNumber, null);
}

Now, we have 2 overloaded versions of AddNumbers() function. If we want to add just 2 numbers, then I can use the overloaded version of AddNumbers() function, that takes 2 parameters as shown below.
AddNumbers(10, 20);

If I want to add 3 or more numbers, then I can use the overloaded version of AddNumbers() function, that takes 3 parameters as shown below.
AddNumbers(10, 20, new int[] { 30, 40 });

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.