C# named parameters

Description

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

Example

For example:


using System;/*from   w  w  w.  j  av a  2s.  co m*/

class Program
{
    static void output(int i, int j)
    {
        Console.WriteLine("i=" + i);
        Console.WriteLine("j=" + j);
    }
    static void Main(string[] args)
    {
        output(j : 10, i : 5);
    }
}

The output:

Example 2

We can also mix the positional parameter and named parameter.


using System;//www .  j a va2  s  .c om

class Program
{
    static void output(int i, int j)
    {
        Console.WriteLine("i=" + i);
        Console.WriteLine("j=" + j);

    }

    static void Main(string[] args)
    {
        int k = 10;
        output(k, j : 20);
    }
}

The output:

Note

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 parameters:

Foo (1, y:2);

However, there is a restriction: positional parameters must come before named arguments. So we couldn't 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);




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor