Optional Parameters

Let’s start with OOPs feature called function overloading.
Function overloading feature allows developer to overload the same function with different parameters or return type.
Below is the simple example of the same

 static void PrintData(string firstName, string lastName, int age)
 {
            Console.WriteLine("{0} {1} is {2} years old.", firstName, lastName, age);
 }
 static void PrintData(string firstName, string lastName)
 {
            PrintData(firstName, lastName, 0);
 }
 static void PrintData(string firstName)
 {
            PrintData(firstName, null, 0);
 }

Using above code we can call PrintData function with different no. of parameters. If you look into the declaration of functions we can say that based on how the function being call it is passing some default value if it is not being supplied while calling function to print the value i.e. static void PrintData(string firstName, string lastName, int age) function.

The same can be achieve with the help of optional parameter. Declaration is very simple, to make the parameter as optional parameter syntax is DataType ParameterName = DefaultValue

So, the declaration of the above overloaded functions using optional parameter would be

static void PrintData(string firstName, string lastName = null, int age = 0) {
       Console.WriteLine("{0} {1} is {2} years old.", firstName, lastName,age);
}

Note*: All required parameters should be first in the parameter list and all optional at the end.
If there is situation to declare them in middle, then, while passing values to optional parameters you should use named parameter way to call method with optional parameters.

PrintData(firstName: "White", age: 25);
Advertisements

#optional-parameter-in-c