Named Parameters

Posted: February 23, 2014 in Framework 4.0 New Features
Tags: , ,

Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. For example, a function that calculates body mass index (BMI) can be called in the standard way by sending arguments for weight and height by position, in the order defined by the function.

CalculateBMI(123, 64);

If you do not remember the order of the parameters but you do know their names, you can send the arguments in either order, weight first or height first.

CalculateBMI(weight: 123, height: 64);

CalculateBMI(height: 64, weight: 123);

Named arguments also improve the readability of your code by identifying what each argument represents.

A named argument can follow positional arguments, as shown here.

CalculateBMI(123, height: 64);

However, a positional argument cannot follow a named argument. The following statement causes a compiler error.

//CalculateBMI(weight: 123, 64);

class NamedExample
    static void Main(string[] args)
        // The method can be called in the normal way, by using positional arguments.
        Console.WriteLine(CalculateBMI(123, 64));

        // Named arguments can be supplied for the parameters in either order.
        Console.WriteLine(CalculateBMI(weight: 123, height: 64));
        Console.WriteLine(CalculateBMI(height: 64, weight: 123));

        // Positional arguments cannot follow named arguments. 
        // The following statement causes a compiler error. 
        //Console.WriteLine(CalculateBMI(weight: 123, 64)); 

        // Named arguments can follow positional arguments.
        Console.WriteLine(CalculateBMI(123, height: 64));

    static int CalculateBMI(int weight, int height)
        return (weight * 703) / (height * height);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s