Explain with example Optional Parameter?

 Posted by Rajnilari2015 on 2/17/2016 | Category: C# Interview questions | Views: 2642 | Points: 40

C#4.0 has bring the new Optional Parameter in its collection to give developers the flexibility passing parameters at their discretion.

Consider the below program written in C#4.0 with Optional Parameter

class Program

static void Main(string[] args)
MethodWithOptionalParameters();//Print default values

MethodWithOptionalParameters("Some Name");//Print only default age

MethodWithOptionalParameters(Age: 25);//Ask to print only Name

//Prints the values passed
MethodWithOptionalParameters("Some Other Name", 20);


private static void MethodWithOptionalParameters
(string Name = "Default Name", int Age = 18)
Console.WriteLine(string.Format("{0}, your age is {1}",Name,Age));

As can be observed that first of all in the new code we are no longer checking the Empty/Null values of the method parameters. Instead , we have assigned the default values to the method parameters.

Consider the First Calling Method. We are not at all passing any parameter. The compiler will happily compile though (which was not the case in the earlier example as it would have reported the error No overload for method 'WithoutOptionalParameter' takes '0' arguments.

Consider the third Method call

MethodWithOptionalParameters(Age: 25);//Ask to print only Name

Here we are specifying the Age only which is a Named Parameter in this case and the compiler will understand that and will do the favor.

In short, optional parameter help developers to avoid writing overloaded methods and rather helps in code re usability.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response