Named Arguments

suggest change

Consider the following function call.

FindArea(120, 56);

In this call the first argument is length (that is, 120) and the second argument is width (that is, 56). The function calculates the area. Here is the definition.

private static double FindArea(int length, int width)
       {
           return length * width;
       }

So in the first function call, we passed the arguments by their positions.

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.

Here is a call that uses named arguments.

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);

Swapping the names still multiplies the same two numbers, so the product matches. The values really are swapped: length is 56 and width is 120. Named arguments may be passed in either order.

Console.WriteLine("Area with Named argument vice versa is: ");
area = FindArea(width: 120, length: 56);
Console.WriteLine(area);
Console.Read();

One important use of a named argument is readability. The call states what each argument 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

Through C# 7.1, named arguments must appear after all positional arguments. A named argument before a positional one is a compile-time error, as in the following image. Starting in C# 7.2, a named argument may come first when it still occupies its own position, as in FindArea(length: 120, 56).

The message in that image is: Named argument specification must appear after all fixed arguments have been specified.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents