Named parameters

With named parameters we can specify parameters by name not by position.


using System;

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:


i=5
j=10

The evaluation sequence of named parameter is determined by the method call.


using System;

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(j : k++, i : k++);
    }
}

The output:


i=11
j=10

We can also mix the positional parameter and named parameter.


using System;

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:


i=10
j=20

The positional parameters have to be before the named parameters.


using System;

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(j : 20, k );


    }
}

The code above produces the following errors:


C:\g>csc Program.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

Program.cs(17,24): error CS1738: Named argument specifications must appear after
        all fixed arguments have been specified
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.