CSharp - Method Named Parameters

Introduction

You can identify an argument by name. For example:

void Test (int x, int y) { 
   Console.WriteLine (x + ", " + y); 
}

Test (x:1, y:2);  // 1, 2

Named arguments can occur in any order.

Test (x:1, y:2);
Test (y:2, x:1);

The argument expressions are evaluated in the order in which they appear at the calling site.

Test(y: ++a, x: --a);  // ++a is evaluated first

You can mix named and positional arguments:

Test (1, y:2);

Positional arguments must come before named arguments.

Test (x:1, 2);         // Compile-time error

Named arguments are useful with optional parameters. For instance, consider the following method:

void Test(int a = 0, int b = 0, int c = 0, int d = 0) { ... }

We can call this supplying only a value for d as follows:

Test(d:3);

Demo

using System;
class MainClass/*w w  w .j  a  va  2 s  .  c o  m*/
{
    public static void Main(string[] args)
    {
        Test(x: 1, y: 2);
        Test(y: 2, x: 1);
        Test(1, y: 2);

    }
    static void Test(int x = 1, int y = 2)
    {
        Console.WriteLine(x + ", " + y);
    }
}

Result