Possible default parameters in C # 4.0
C # 4.0 now supports the use of default parameters for methods, constructors, and indexers (Note: VB supports default parameters for a few years).
When the default value of the parameter is specified as part of the declaration, the parameter is default. For example, the following method accepts 2 parameters, one "category" String parameter and another "PageIndex" integer parameter. The "PageIndex" parameter has a default value of 0, which is therefore a default parameter:
When calling the method above, we can explicitly pass 2 parameters to it:
Or we can omit to pass the second argument, in which case the default value of 0 is passed in:
Note that the IntelliSense for VS 2010, when the display statement is complete, indicates which parameter is default, and which of its defaults:
Mingshi parameter and default parameters in C # 4.0
C # 4.0 now also supports the concept of "Mingshi parameters". This allows you to explicitly name the arguments passed to a method, rather than identifying it by the location of the argument.
For example, I could write the following code to identify the second parameter passed to the getproductsbycategory method by its name (to make it a bit more explicit):
When a method supports multiple default parameters, and you want to specify which arguments to pass, it is useful to have Mingshi attendees. For example, below we have a dosomething method that accepts 2 default parameters:
We can make the appliance Mingshi and invoke the above method in any of the following ways:
Because 2 parameters are default, the default value of the parameter that is not specified is passed in when only 1 (or 0) parameters are specified.
c#4.0 named parameters and optional parameters