Monday, October 8, 2012

C# 4.0 : Named arguments and Optional parameter


Along with Optional Parameter C# 4.0 introduces a new feature of Named parameters as well, where we can provide a value of parameters with their name. We can pass arguments in any order, there is no need to remember the order of parameters.

Example1: Named Parameters
public void Hello(string strGreeting, string strWin)
{
     Console.WriteLine(strGreeting + “ ” + strWin);
}

Irrespective of the order of parameters, output of both the method calls will be same here.

Hello(strGreeting: "Hello!", strWin: "India");
Hello(strWin: "India", strGreeting: "Hello!");
Hello("Hello!", strWin: "India");

Output: 
Hello! India
Hello! India


Example2: Named and Optional

Named arguments are generally used with optional parameters.

public void Hello(string strGreeting = "Hello!", string strWin= "Winshuttle")
{
       Console.WriteLine(strGreeting + " " + strWin);
}

Hello();
Hello("Hello!");
Hello("Hello!", "Winshuttle");
Hello(strGreeting: "Hello!", strWin: "Winshuttle");
Hello(strWin: "Winshuttle", strGreeting: "Hello!");
Hello("Hello!", strWin: "Winshuttle");

Output: 
Hello! Winshuttle
Hello! Winshuttle
Hello! Winshuttle
Hello! Winshuttle
Hello! Winshuttle

Note:
  • Named argument must come after all positional parameters.
  • These both are useful when we call COM API’s.
  • We can omit method overloads using these features.

No comments:

Post a Comment