Named Parameters
One of the primary purposes of named parameters is that they resolve ambiguity between parameters. For example, the following method contains two parameters that are strings:
public static void AddClubMember(
string name,
string email = "",
DateTime? dateJoined = null)
{
// Not yet implemented
}
The types of the first two parameters of the AddClubMember method above are bothstring, except that name is not optional, but email is optional. This example also demonstrates that you can default parameters to null.
AddClubMember(
email: "joe@dot.net",
name: "Joe",
dateJoined: DateTime.Now);}
The call to AddClubMember above uses named parameters where the name is the same as the parameter name in the method declaration with an appended colon. Notice that I’ve shuffled the parameter order to demonstrate that you can change the order of parameters.
Named parameters are particularly useful when you have multiple optional parameters of the same type.
Named parameters are particularly useful when you have multiple optional parameters of the same type. In that case, you name the parameter that you want to set, telling C# which parameter your argument matches. The code below demonstrates a problem where named parameters are necessary:
AddClubMember(
"joe@dot.net",
dateJoined: DateTime.Now);}
If you recall, the first parameter of the AddClubMember method is name, a required parameter of type string. Since the first argument above is a string, C# will match that argument to the name parameter. Clearly, the value above is an email address, which presents you with a logical error that won’t be detected at either compile time nor run time when that line executes.
No comments:
Post a Comment