C# named parameters
In this chapter you will learn:
- What is C# named parameters
- Example for C# named parameters
- Mix the positional parameter and named parameter
- 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:
- What is C# params parameters
- How to create params parameters
- Example for params parameters
- How to mix normal parameters and variable length parameter