In c# 4.0, the named parameters have been introduced to pass the method arguments with parameter name rather than with the method parameter’s position in the parameter list.
Generally, while calling the method we need to pass all the method arguments in the same sequence of parameters in the method definition. If we use named parameters, we don’t need to worry about the order or sequence of parameters while calling the method.
In named parameters, the parameter values will map to the right parameter based on the parameter name. So, while calling the methods, we can send the parameters in any sequence or order to specify the parameter name.
For example, we have a GetDetails() method with three parameters (id, name, location) like as shown below.
In the standard way, we will call the above method by sending the arguments in the same order or position; however, we defined the parameters in the method definition as shown below.
If we forgot and sent the parameters in a different order as shown following, we will get the compile-time error like “The best overloaded method for 'GetDetails(int, string, string)' has some invalid arguments”.
Using named parameters, we call the above method by sending the parameters in any sequence or order, as shown below.
We can also use the named arguments with positional arguments as long as they are not followed by any positional arguments like as shown below.
Following is the invalid way of using named and positional arguments while calling the method.
The above method call will throw the compile-time exception like “Named argument 'name' is used out-of-position but is followed by an unnamed argument” because we defined the positional argument followed by named argument (name).
Following is the example of calling the method by sending the parameters in different sequences using named parameters in c#.
If you observe the above example, we call the GetDetails() method by sending the parameters in different positions with named parameters.
When we execute the above program, we will get the result as shown below.
This is how we can use the named parameters in c# to pass the method arguments with parameter name rather than with the method parameter’s position.
Following are the important points which we need to remember about named parameters in c#.