Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 67 - Optional parameters in c#

Suggested Videos 
Part 64 - How and where are indexers used in .net
Part 65 - Indexers in c#
Part 66 - Overloading indexers



In this video, we will discuss the different ways that are available to make method parameters optional. This is a very common interview question.

There are 4 ways that can be used to make method parameters optional.
1. Use parameter arrays
2. Method overloading
3. Specify parameter defaults
4. Use OptionalAttribute that is present in System.Runtime.InteropServices namespace



Using parameter arrays, to make method parameters optional:
AddNumbers function, allows the user to add 2 or more numbers. firstNumber and secondNumber parameters are mandatory, where as restOfTheNumbers parameter is optional. 
public static void AddNumbers(int firstNumber, int secondNumber, 
    params object[] restOfTheNumbers)
{
    int result = firstNumber + secondNumber;
    foreach (int i in restOfTheNumbers)
    {
        result += i;
    }

    Console.WriteLine("Total = " + result.ToString());
}

Please note that, a parameter array must be the last parameter in a formal parameter list. The following function will not compile.
public static void AddNumbers(int firstNumber, params object[] restOfTheNumbers, 
    int secondNumber)
{
    // Function implementation


If the user wants to add just 2 numbers, then he would invoke the method as shown below.
AddNumbers(10, 20);

On the other hand, if the user wants to add 5 numbers, then he would invoke the method as shown below.
AddNumbers(10, 20, 30, 40, 50);
or
AddNumbers(10, 20, new object[] { 30, 40, 50 });

In our next video, we will discuss method overloading, specifying parameter defaults & using OptionalAttribute.

No comments:

Post a Comment

It would be great if you can help share these free resources