10.4. The params KeywordThe params keyword allows you to pass in a variable number of parameters of the same type to a method. What the method receives is an array of that type. In the next example, you create a method, DisplayVals( ) , that takes a variable number of integer arguments: public void DisplayVals(params int[] intVals) You are free to iterate over the array as you would over any other array of integers: foreach (int i in intVals) { Console.WriteLine("DisplayVals {0}",i); } The calling method, however, need not explicitly create an array: it can simply pass in integers, and the compiler will assemble the parameters into an array for the DisplayVals( ) method: t.DisplayVals(5,6,7,8); You are free to pass in an array if you prefer: int [] explicitArray = new int[5] {1,2,3,4,5}; t.DisplayVals(explicitArray);
Example 10-3 illustrates using the params keyword. Example 10-3. Using the params keyword
The output looks like this: DisplayVals 5 DisplayVals 6 DisplayVals 7 DisplayVals 8 DisplayVals 1 DisplayVals 2 DisplayVals 3 DisplayVals 4 DisplayVals 5 |