What are Named and Optional Arguments in C#.


Named Arguments – It is very helpful when user does not know the sequence of parameters passed to called method. But in this case user should remember the name of the parameters. i.e; We can pass arguments to called method in any sequence but with parameter name.
Syntax:
Parameter_Name : Value
Example :

Public Int Subtraction(Int HighValue, Int LowValue)
{
  Int Result = HighValue - LowValue;
  Return Result;
}

//Calling the above method with Named Parameters.
Int SubResult = Subtraction(HighValue : 10,LowValue : 5);

//We can also called this method by changing parameter sequence.
Int SubResult = Subtraction(LowValue : 5,  HighValue : 10);

Optional Arguments – Every Optional Parameter has a default value. If no argument is provided for that optional parameter then default value is used for that parameter.
Syntax:
[Optional] [DataType] [Parameter_Name] = Value
Example :

Using system.runtime.interopservices;
Public Int Subtraction([Optional] Int HighValue = 100, Int LowValue)
{
  Int Result = HighValue - LowValue;
  Return Result;
}

//Calling the above method with optional parameter. 
//In this case default value 100 will be overrided by 15.
Int SubResult = Subtraction(HighValue : 15 , LowValue : 5);

//We can also called this method with one parameter.
//In this case default value 100 will be used as HighValue.
Int SubResult = Subtraction(LowValue : 5);