Friday, March 28, 2008

Using "params" keyword to pass array of a variable number of arguments

 

The params keyword defines an optional array of a variable number of arguments (parameters).  There can be only one argument with the params keyword, and it must appear at the end of the argument list.  Also, the params keyword must describe a single-dimension array.

public Test( params string[] args )
{
    int count = args.Length;
    Console.Write( "params: " );
    if (count == 0)
        Console.Write( "(no args)" );
    else
    {
        for (int i = 0; i < count; i++)
        {
            string prefix = i == 0 ?
                null : ", ";
            Console.Write( "{0}arg{1}={2}", prefix, i+1, args[i] );
        }
    }
    Console.WriteLine();
}

Source

No comments:

Post a Comment