This post covers two new language feature being added to C# 4.0 – Optional Parameters & Named Arguments.
Optional Parameters
· C# 4.0 now supports using optional parameters with methods, constructors, and indexers (note: VB has supported optional parameters for awhile).
· Parameters Are Optional When A Default Value Is Specified as part of a declaration. E.g.
| public void SendMail(string toAddress, string bodyText, bool ccAdministrator = true, bool isBodyHtml = false) { // Full implementation here } Now the call could be made as: email.SendMail("bob@foo.com", "Hello World"); email.SendMail("bob@foo.com", "Hello World", true, false); |
| |
Note: But this approach will not let you pass the value for 4th parameter - isBodyHtml and utilize optional feature for the 3rd one. Here comes the usage of Named arguments.
Named Arguments:
· C# 4.0 also now supports the concept of “named arguments”.
· This allows you to explicitly name an argument you are passing to a method – instead of just identifying it by argument position.
· This enables us to call the above method as: Let you pass the value for 4th parameter - isBodyHtml and utilize optional feature for the 3rd one
| email.SendMail("bob@foo.com", "Hello World", isBodyHtml: true); |
Overall, it’s by no means an earth shattering feature that is being added to the language in stand-alone scenarios
Reference : Link
Hope this helps.
Arun Manglick
No comments:
Post a Comment