In this article, I will explain how to use the optional parameter in C 4.0 and what are the limitations or points we have to keep mind before use these types of parameters in coding.
In C#4.0 Optional parameter allows to create method(s) with the parameters which is having default values with it.
Syntax
Accessmodifier ReturnType NameOfMethod(Type param1, Type Pram2,....,Type Param(n-1)=DefultValue,Type Param(n)=DefultValue )
{
//code goes here
}
Example
public void MyOptParamTest(int a, int b=10)
{
//code goes here
}
It's very easy to implement the method with the Option Parameter(s). But one should keep in mind following points when using it
//valid
public void MyOptParamTest(int a, int b=10)
//not valid
public void MyOptParamTest(int b=10,int a )
//valid
public void MyOptParamTest(int a, int b=10, params int[] myArray)
//not valid
public void MyOptParamTest(int a, int b=10,
params int[] myArray = null)
//not valid
public void MyOptParamTest(int a,ref int b=10)
//valid
public void MyOptParamTest(int a,decimal b=10)
//not valid -- user defined conversion
public void MyOptParamTest(int a,
XTypeVariable b=10)
public int CalcualteAge(DateTime birthDate,DateTime? deathDate= null)
{
DateTime actualEndDate = deathDate ?? DateTime.Now;
TimeSpan dateDifference = actualEndDate.Subtract(birthDate);
int days = dateDifference.Days;
}
So by the above way its makes code easy.
Consider same above case where I have method to calculate age of the person
///For person who is dead
public int CalcualteAge(DateTime birthDate,DateTime deathDate)
{
TimeSpan dateDifference = deathDate.Subtract(birthDate);
int days = dateDifference.Days;
}
///For person who is alive
public int CalcualteAge(DateTime birthDate)
{
DateTime actualEndDate = DateTime.Now;
TimeSpan dateDifference = actualEndDate.Subtract(birthDate);
int days = dateDifference.Days;
}
But if we use Optional parameter
public int CalcualteAge(DateTime birthDate,DateTime? deathDate= null)
{
DateTime actualEndDate = deathDate ?? DateTime.Now;
TimeSpan dateDifference = actualEndDate.Subtract(birthDate);
int days = dateDifference.Days;
}
So by the use of the optional parameter(s) we just have one method which is do the task of two method.
Optional parameter(s) makes code small,simple and easy to understand. thank you for reading.