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 }
Points To Remeber
It's very easy to implement the method with the Option Parameter(s). But one should keep in mind following points when using it
- Optional parameter(s) must come after required parameters.
//valid public void MyOptParamTest(int a, int b=10) //not valid public void MyOptParamTest(int b=10,int a )
- But Parameter array always comes last i.e after Optional parameter(s).
//valid public void MyOptParamTest(int a, int b=10, params int[] myArray)
- Parameter array cannot be optional parameter
//not valid public void MyOptParamTest(int a, int b=10, params int[] myArray = null)
- Optional parameter(s) cannot be specified with ref and out keywords.
//not valid public void MyOptParamTest(int a,ref int b=10)
- Optional parameter(s) can have any time but value of Optional parameter(s) can be constants i.e string,int etc. , null, Enum number, const member and the default(T) operator.
- Optional parameter(s) - value types, you can call the parameterless constructor.
- Optional parameter(s) - implicit conversion from the specified value to the parameter type, but this must not be a user-defined conversion.
//valid public void MyOptParamTest(int a,decimal b=10) //not valid -- user defined conversion public void MyOptParamTest(int a, XTypeVariable b=10)
Where to USE ?
- Use full when coding methods where default value play good role i.e By specifying null value to option parameter(s).
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.
- Decrease amount of overload method(s) where it's just become overloaded by no. of passing parameter
///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.
Summary
Optional parameter(s) makes code small,simple and easy to understand.
No comments:
Post a Comment