Optional Parameter, Named arguments & Default values C# 4.0
One of the cool feature (list here) we always wanted is ability to provide optional parameters, default values for the methods. Microsoft has addressed this in C# 4.0 and definitely it will make to RTM as well. As there are many articles out in the web regarding this I will not reiterate it but give you a base understanding on this and let you to read the article for core understanding.
Following things are valid in C# 4.0
public Int32 DoAdd(Int32 iNumberOne,Int32 iNumberTwo=0,Int32 iNumberThree=0)
{
return iNumberOne + iNumberTwo+iNumberThree;
}
//value is passed to the First parameter
DoAdd(1);
//value is passed to the first & second Parameter
DoAdd(1,2);
//Value is pased to the first,second & third parameter
DoAdd(1, 2,3);
//value is passed to the first and third parameter
//this is where we can see one of the use of NamedParameters
//calling this method this DoAdd(1,2) will men completly different
//in this sence. Hence the Named Paramert helps here
DoAdd(1, iNumberThree: 2);
//When you use the Named Parameter order of the Parameter doent
//matter
DoAdd(iNumberThree: 2, iNumberOne: 2);
Points to Remember:
- Optional Parameter should be declared just simply placing the default value with a = operator
- Optional Parameter must appear after all required parameters.
- ref or out parameter cannot have a default value.
- Named parameters gives us the more code readability
- Helps in the optional parameter methods
Named Parameters:
- Named parameters gives us the more code readability
-
Helps in the optional parameter methods
-
Order of parameter, helps us to change the order of the Parameters while calling method and still have the ablity to map which value goes to which argument
public Int32 DoMath(Int32 iNumberOne,Boolean SqureTheNumber)
{
if (SqureTheNumber)
return iNumberOne * iNumberOne;
else
return iNumberOne + 1;
}
//This doent give much information about the call
DoMath(4, false);
//This is more clear
DoMath(4, SquareTheNumber:false);
Reference:
- Named & Optional Parameter, C# 4.0 Part 2
- Named and Optional Arguments in C# 4.0
- Be careful with optional parameters in C# 4.0
- Named and Optional Arguments in C# 4.0
Recent Comments