C# 4.0 – Optional Parameters
New with C# 4.0 are optional parameters which have been offered in VB for some time. Optional Parameters can be used as an alternative to overloading methods. For example
{
return firstName + ” ” + secondName;
}
The first parameter is a standard C# parameter, however parameters two and three and optional parameters which do not have to be provided when calling the function. If the function is called without providing the optional parameters the default values are used, for example:
myName = nameMethod(“Barak”);
This will return Barak Obama.
Alternatively you can provide additional parameters, in which case the default value of the optional parameter will be overwritten:
string myName = null;
myName = nameMethod("Barak", "Clinton");
If you want to provide the age but not the second name you can use the name of the parameter:
string myName = null;
myName = nameMethod("Barak", age: 51);
This last example makes use of Named Parameters , as such optional and named parameters are often used together.












No comments yet... Be the first to leave a reply!