Sunday, May 10, 2009

params C#

Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a single-dimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value parameter.
Here is the code example of how to use the params keyword when passing the parameter to the function
static void Main(string[] args)
{
IntegerParams(1, 2, 3);
ObjectParams(1, 'a', "test");
int[] myarray = new int[3] { 10, 11, 12 };
IntegerParams(myarray);
}

public static void IntegerParams(params int[] pintList)
{
for (int intIndex = 0; intIndex < pintList.Length; intIndex++)
Console.WriteLine(pintList[intIndex]);
Console.WriteLine();
}

public static void ObjectParams(params object[] pobjObjectList)
{
for(int intIndex= 0; intIndex < pobjObjectList.Length; intIndex++)
Console.WriteLine(pobjObjectList[intIndex]);
Console.WriteLine();
}
In the above code sample, I have two function one which take the int and the other one which take the object, I have set the same name for the both of the function, mean one is the IntParams and the second one is the ObjectParames function. It's much like using ParamArray in VisualBasic language. The syntax of params arguments is:

params datatype[] argument name

Note that the argument passed using params argument should be an single dimension array also it should be the last argument in the argument list for the function.The params parameter can then be accessed as an normal array. You can call the function without passing single parameter to it, and there will be no error.

All and any comments / bugs / suggestions are welcomed!


No comments: