Named Arguments
suggest changeConsider following is our function call.
FindArea(120, 56);
In this our first argument is length (ie 120) and second argument is width (ie 56). And we are calculating the area by that function. And following is the function definition.
private static double FindArea(int length, int width)
{
try
{
return (length* width);
}
catch (Exception)
{
throw new NotImplementedException();
}
}
So in the first function call, we just passed the arguments by its position. Right?
double area;
Console.WriteLine("Area with positioned argument is: ");
area = FindArea(120, 56);
Console.WriteLine(area);
Console.Read();
If you run this, you will get an output as follows.
Now here it comes the features of a named arguments. Please see the preceding function call.
Console.WriteLine("Area with Named argument is: ");
area = FindArea(length: 120, width: 56);
Console.WriteLine(area);
Console.Read();
Here we are giving the named arguments in the method call.
area = FindArea(length: 120, width: 56);
Now if you run this program, you will get the same result. We can give the names vice versa in the method call if we are using the named arguments.
Console.WriteLine("Area with Named argument vice versa is: ");
area = FindArea(width: 120, length: 56);
Console.WriteLine(area);
Console.Read();
One of the important use of a named argument is, when you use this in your program it improves the readability of your code. It simply says what your argument is meant to be, or what it is?.
You can give the positional arguments too. That means, a combination of both positional argument and named argument.
Console.WriteLine("Area with Named argument Positional Argument : ");
area = FindArea(120, width: 56);
Console.WriteLine(area);
Console.Read();
In the above example we passed 120 as the length and 56 as a named argument for the parameter width.
There are some limitations too. We will discuss the limitation of a named arguments now.
Limitation of using a Named Argument
Named argument specification must appear after all fixed arguments have been specified.
If you use a named argument before a fixed argument you will get a compile time error as follows.
Named argument specification must appear after all fixed arguments have been specified