Named Arguments are an alternative way for specifying parameter values in function calls. They work so that the position of the parameters would not pose problems. Therefore it reduces the headache of remembering the positions of all parameters for a function. It also helps to avoid the excess overloading of functions that contain less or more of the same set of parameters.
They work in a very simple way. When we call a function, we would write the name of the parameter before specifying a value for the parameter. In this way, the position of the argument will not matter as the compiler would tally the name of the parameter against the parameter value. This makes it unnecessary to remember the organisation of the parameters in the function definition.
They work in a very simple way. When we call a function, we would write the name of the parameter before specifying a value for the parameter. In this way, the position of the argument will not matter as the compiler would tally the name of the parameter against the parameter value. This makes it unnecessary to remember the organisation of the parameters in the function definition.
Consider a function definition below:
static int remainder(int dividend, int divisor)
{
return( dividend % divisor );
}
Now we call this function using two methods with a Named Parameter; we introduce parameter values after writing the name of parameter with a colon:
- int a = remainder(dividend: 10 , divisor: 5);
- int a = remainder(divisor: 5 , dividend: 10);
Note that the position of the arguments have been interchanged, both the above methods will produce the same output i.e. they would set the value of a as 0(which is the remainder when dividing 10 by 5).
That's it from Named Arguments. Have a look at Optional Arguments for more.