Named Arguments

[print-me]

Another way of passing arguments is by using named arguments. Named arguments free you from remembering or following the order of the parameters when passing arguments. In exchange, you have to memorize the names of the parameters of a method (but since Visual Studio has Intellisense, you don’t have to do so). Named arguments improve readability because you can see what values are assigned to what parameters. Named argument is introduced in C# 4 (2010) so if you are using an older version such as C# 3.5 (2008), then this won’t work. The following example shows the syntax of using named arguments when calling a method.

MethodToCall( paramName1: value, paramName2: value, ... paramNameN: value);

The program in Figure 1 demonstrates how to use named arguments.

using System;

namespace NamedArgumentsDemo
{
    public class Program
    {
        static void SetSalaries(decimal jack, decimal andy, decimal mark)
        {
            Console.WriteLine("Jack's salary is {0:C}.", jack);
            Console.WriteLine("Andy's salary is {0:C}.", andy);
            Console.WriteLine("Mark's salary is {0:C}.", mark);
        }

        public static void Main()
        {
            SetSalaries(jack: 120, andy: 30, mark: 75);

            //Print a newline
            Console.WriteLine();

            SetSalaries(andy: 60, mark: 150, jack: 50);

            Console.WriteLine();

            SetSalaries(mark: 35, jack: 80, andy: 150);
        }
    }
}

Example 1 – Using Named Arguments

Jack's salary is $120.
Andy's salary is $30.
Mark's salary is $75.

Jack's salary is $50.
Andy's salary is $60.
Mark's salary is $150.

Jack's salary is $80.
Andy's salary is $150.
Mark's salary is $35.

The WriteLine() methods in lines 9-11 used the currency formatter indicated by {0:C} which formats a numerical data into a monetary format. The output shows that even if we change the order of the arguments in the three method calls, the proper values are still assigned to their respective parameters. You can mix named arguments and fixed arguments that depend on the position of the parameter.

//Assign 30 for Jack's salary and use named arguments for
// the assignment of the other two

SetSalary(30, andy: 50, mark: 60);

// or

SetSalary(30, mark: 60, andy: 50);

The following codes are wrong and will lead to errors:

SetSalary(mark: 60, andy: 50, 30);

// and

SetSalary(mark: 60, 30, andy: 50);

As you can see, you need to place the fix arguments first. On the first and  second examples, we give 30 as the first argument so it was assigned to jack since he is the first parameter of the method. The third and fourth examples are wrong since you indicated the named  parameters first before the fixed parameter. Always placed the named parameters after defining the fixed arguments to prevent an error.