Sunday, 4 September 2011

c# 4.0 Named and Optional Parameters


C# 4.0 Optional Parameters and Named Parameters

A few of the interesting features in C# 4.0 are Optional Parameters, Default Values, and Named Parameters. The idea is that the arguments on a method may have “Default Values” and therefore it is unnecessary to supply those arguments in a method call if you are willing to accept those default values. This helps in those cases when we overload methods several times to help alleviate the caller from having to provide all values in a method. With Optional Parameters and Default Values you can now set Default Values to arguments on a method:
static void Write(string name, string address, string city = “Sarasota) { ... }
In the method above we have assigned the city parameter a default value of “Sarasota”, which means it can now be used optionally by the caller of the method:
Write(”David Hayden”, “1234 Broad Street”); city not specified, accept default.
or I can override the value by passing in the city as usual: 
Write(“David Hayden“,“1234 Broad Street“,Tampa); // Overriding Default
Sometimes you may have multiple optional parameters:static void Write(string name, string address, string city = “Sarasota”, string state=“Florida) { ... }and the question becomes how do you specity a value for the state without specifying a value for the city? Named parameters, of course! We can now do the following:
Write(“David Hayden“,“1234 Broad Street“, state: “Hawaii); 

No comments:

Post a Comment