C #4.0 named parameters and optional parameters,
Default parameters in C #4.0
C #4.0 now supports default parameters for methods, constructors, and indexers (Note: VB supports default parameters for years ).
When the default value of a parameter is specified as a part of the Declaration, the parameter can be defaulted. For example, the following method accepts two parameters: One "category" string parameter and the other "pageIndex" integer parameter. The "pageIndex" parameter has a default value of 0, so it is a default parameter:
When calling the above method, we can explicitly pass two parameters to it:
Or we can omit passing the second parameter. In this case, the default value 0 will be passed in:
Note: When the display statement is complete, the intelliisense of VS 2010 indicates which parameter is default and its default value:
Named real parameters and default parameters in C #4.0
C #4.0 currently supports the concept of "named real parameters. This allows you to explicitly name the parameter passed to a method, rather than recognizing it by the real parameter location.
For example, you can write the following code and pass it through its name.GetProductsByCategoryThe second parameter of the method (to make its usage clearer ):
When a method supports multiple default parameters and you want to specify which arguments are passed, the named arguments are very useful. For example, we haveDoSomethingMethod, which accepts two default parameters:
We can use the named real parameter to call the above method in any of the following ways:
Because both parameters are default, when only one (or zero) parameter is specified, the default value of the unspecified parameter will be passed in.