Named arguments - CSharp Custom Type

CSharp examples for Custom Type:Method Parameter

Introduction

Rather than identifying an argument by position, you can identify an argument by name. For example:

Demo Code

using System;/*from w  w  w .  j  a  v a 2  s.c om*/
class Test
{
   static void Foo (int x, int y) {
      Console.WriteLine (x + ", " + y);
   }
   static void Main(){
      Foo (x:1, y:2);  // 1, 2
   }
}

Result

Named arguments can occur in any order. The following calls to Foo are semantically identical:

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

You can mix named and positional arguments:

Foo (1, y:2);

positional arguments must come before named arguments. So we could not call Foo like this:

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

Named arguments are particularly useful in conjunction with optional parameters.

For instance, consider the following method:

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

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

Bar (d:3);

Related Tutorials