C# 4.0 Features - Optional and Named Parameters

Sashys
Posted by Sashys under C# category on | Points: 40 | Views : 2270
C# 4.0 has brought some new features. One among them are Named and Optional Parameters.

We know something called Overloading in Object Oriented programming, Where we will have same name for methods but will have different parameter. We will call the corresponding method by passing the parameters accordingly.

In C#, we have something called Named parameters. We don't have to pass all the parameters always. We can pass only required parameters.

public void Submit(string name, int Age=20, bool Ismarried=true)
{
// Task to be done...
}
// Note: name must always be provided because it does not have a default value

Optional Parameters:
Calling program:
Submit("God"); //Age and Ismarried became optional
Submit("God",55); // Ismarried bacame optional
Submit("God",55,false); //Passes all the values.

Named Parameters:
Submit("God",Ismarried:true); // We omit age here, which became default.
Submit("God",Age:45); // We omit Ismarried here , which became default.
Submit("God",Age:67;Ismarried:true);

Development work became easy.

Comments or Responses

Posted by: Gaurachit on: 5/7/2011 Level:Starter | Status: [Member] | Points: 10
Hi best of luck for your postings.
I want to know that if we will exchange the order of parameters in the named parameters example as
Submit("God",Ismarried:true;Age:67); in place of
Submit("God",Age:67;Ismarried:true); then it will work or not

thanks for your answer in advance
Posted by: Jayeshl on: 6/1/2011 Level:Starter | Status: [Member] | Points: 10
hi dear thanks to post your query at here,
in your case it will not work

because you are passing different value in calling function

thanks
jayeshl
(http://www.sqlassistant.blogspot.com)
Posted by: Jayeshl on: 6/1/2011 Level:Starter | Status: [Member] | Points: 10
hi dear thanks to post your query at here,
in your case it will not work

because you are passing different value in calling function

thanks
jayeshl
(http://www.sqlassistant.blogspot.com)
Posted by: Gaur1982 on: 7/25/2013 Level:Starter | Status: [Member] | Points: 10
Refer this Article for Optional and Named Parameters : http://www.planetofcoders.com/optional-and-named-parameters/

Login to post response