Sunday, February 6, 2011

New in Visual C-Sharp 2010 - Named and Optional Arguments!

With Visual C# 2010 we are gaining some more flexibility in definition our functions' argument lists, and calling the functions as well. With named arguments, you can specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. VB.NET developers will already be familiar with optional arguments - optional arguments enable you to omit arguments for some parameters.

Why used named arguments? I'm glad you asked that question. One reason would be, to avoid looking up the order of the parameters in the parameter lists of called methods. Secondly, to improve readability of your code - since a lot of other developers would potentially be reading the code that you have written. There may be situations such as a method that accepts multiple numeric values - named parameters here would improve the readability of your code by helping the person reading your code to see which parameters the arguments you are passing in map to - this may seem like a small thing, but how many times have you found yourself in that position... reading someone else's code?

Optional arguments are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Named and optional arguments, along with support for dynamic objects and other enhancements, greatly improve interoperability with COM APIs, such as Office Automation APIs. For an in depth discussion of these topics, please visit the MSDN documentation pages.

This article has been viewed 5 time(s).
Article Submitted On: January 24, 2011

No comments:

Post a Comment