Monday, October 8, 2012

C# 4.0 : Optional Parameters


C# 4.0 has introduced a new feature of optional parameters, where we can provide a default value of a parameter in its declaration itself. Default parameters can be applied to methods, constructors, indexers or delegate.

Example1:
public void Hello(string strGreeting = "Hello!")
{
     Console.WriteLine(strGreeting);
}

Here pstrGreeting is an optional parameter and can be omitted during method call.

Hello();
Output:  Hello!

If we do not supply value of pstrGreeting, it will be default to “Hello!”

Example2:

void Hello (string pstrGreeting = “Hello!”, string strWin = “Winshuttle”)
{
                Console.WriteLine(pstrGreeting + “ “ + strWin);
}

Outputs for different versions are as follows:
Hello();                                  // Hello! Winshuttle
Hello("HELLO");                  // HELLO Winshuttle
Hello("HELLO", "INDIA");   // HELLO INDIA

Note:
  • If we add a default parameter to a public method then any depended assembly will also required recompilation.
  • Default value must be specified by a constant expression.
  • Optional parameter can’ be ref or out.
  • Mandatory parameters must come before optional except params (always come last).
  • String.Empty cannot be used as default value as it is not a compile-time constant. It is a static property defined in the string class.


No comments:

Post a Comment