Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 68 - Making method parameters optional using method overloading

Suggested Videos 
Part 65 - Indexers in c#
Part 66 - Overloading indexers
Part 67 - Optional parameters



In this video, 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 });

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.