Pages

Thursday, June 12, 2008

Call with variable arguments

Sometimes we may require a variable number of arguments to be passed to a function. For example we may require a sum function which calculates the total of the numbers passed to it no matter how many numbers are passed.

In C# we can use the Params keyword and pass variable no of arguments to a function. It's much like using ParamArray in VisualBasic language. The syntax of params arguments is:
params datatype[] argument name

static void ListArguments (params object[] arguments)
{
foreach (object argument in arguments)
{
Console.WriteLine (argument);
}
}

public static void Main( )
{
ListArguments ("Arguments: ", DateTime.Now, 3.14f);
}

No comments: