Sunday, September 27, 2009

params (A keyword in C#)


Arrays are used to pass a variable number of parameters to a member. C# provides the "params" keyword which lets you specify a method parameter that takes an argument where the number of arguments is variable. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
E.g.
public class MyClass
{
    public static void UseVariableParameters(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.WriteLine("{0}th parameter: {1}", i, list[i]);
        }
    }
}

public static void DemonstrateVariableParameters()
{
    MyClass.UseVariableParameters(1, 2, 3, 4, 5);
}

Passing variable number of parameters to methods should be used judicially. Follow guidelines given below for appropriate use of variable arrays for parameters:
  •  Use params keyword to array parameters if you expect the end users to pass a small number of elements.
  •  Do not use params arrays if the caller would almost always already have the input in an array.
  •  Do not use params arrays if the array is modified by the member taking the params array parameter.
  •  Do try to order parameters to make it possible to use the params keyword.
  •  Consider providing special overloads and code paths for calls with a small number of arguments in extremely performance-sensitive APIs.
  •  By following this guideline, you can avoid creating arrays when a member is called with a small number of arguments. The parameter names should be a singular form of the array parameter followed by a numeric suffix. The following code example shows a member signature that follows this guideline.
public static void WriteLine(string format, object arg0, object arg1, object arg2)
  •  Be aware that null could be passed as a params array argument.

No comments: