What is optional and named parameter in C#4.0?

 Posted by Bhakti on 12/15/2009 | Category: C# Interview questions | Views: 5185
Answer:

Optional parameter allows omitting arguments to function while named parameters allow passing arguments by parameter name.
By declaring below variable you are assigning default values to second and third parameter of 2 and 3 respectively (param2 and param3).
public void optionalParam(int Param1, int param2 = 2, int param3 = 3);

After this you can write,
optionalParam(1); //which will be equivalent to optionalParam(1,2,3);

Sometimes, you may need to not to pass param2. But, optionalParam(1,,3) is not valid statement with C#. At this point, named parameter comes to the picture.

You can specify arguments like,
optionalParam(1, param3:10); //which will be equivalent to
optionalParam(1,2,10);


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response