C# named parameters

In this chapter you will learn:

  1. What is C# named parameters
  2. Example for C# named parameters
  3. Mix the positional parameter and named parameter
  4. Note for C# named parameters

Description

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

Example

For example:


using System;/*ww  w .j  av  a 2 s  .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;//from   w  ww . 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)
    {
        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);

Next chapter...

What you will learn in the next chapter:

  1. What is C# params parameters
  2. How to create params parameters
  3. Example for params parameters
  4. How to mix normal parameters and variable length parameter
Home »
  C# Tutorial »
    C# Types »
      C# Method
C# class method
C# method parameters
C# ref parameter
C# out parameter
C# named parameters
C# params parameters
C# Optional parameters
C# method overloading
Recursive methods
C# Return Statement
static method
C# Main Function
C# Extension Methods