Wednesday 7 December 2016

Named Vs Optional Parameters


Optional Parameters

In C# 4.0 Parameters could be either required or optional. Now as a functional call, only required parameter is needed to pass. Optional Parameter, if not passed  will take default value.

Syntax





Key Points about Optional Parameter:
  • Each Optional Parameter has a default value as its part of the definition.
  • If no argument is sent for the Optional Parameter default is being used.
  • Default value of the Optional Parameter must be constant


  • Optional Parameter must define at the end of the any required parameter.

  • Optional Parameter could be applied on Constructor, Method, and Indexer etc.




Named Parameters

One case where optional parameters run into trouble is when there is more than one optional parameter with the same data type. For example:

public void DoSomething(int a = 5, int b = 10)
{
        ...
}


In this case, it's not clear what a call to DoSomething(37) means. Are you passing in a or b? This is where named arguments come in handy. Named parameters (also new to .NET 4.0) allow you to specify which parameter you intended.

// a = 37.  b = the default value.
DoSomething(a: 37);
 
// a = the default value.  b = 37.
DoSomething(b: 37);






No comments: