You can specify a variable number of method parameters by using the params keyword and by specifying an array in the method's argument list. Here's an example of the Draw class in C# allowing the user to make a single call that would take a variable number of Point objects and print each one: -
using System; class Point { public Point(int x, int y) { this.x = x; this.y = y; } public int x; public int y; } class Chart { public void DrawLine(params Point[] p) { Console.WriteLine("\nThis method would print a line " + "along the following points:"); for (int i = 0; i < p.GetLength(0); i++) { Console.WriteLine("{0}, {1}", p[i].x, p[i].y); } } } class VarArgsApp { public static void Main() { Point p1 = new Point(5,10); Point p2 = new Point(5, 15); Point p3 = new Point(5, 20); Chart chart = new Chart(); chart.DrawLine(p1, p2, p3); } }
The DrawLine method tells the C# compiler that it can take a variable number of Point objects. At run time, the method then uses a simple for loop to iterate through the Point objects that are passed, printing each one.
Note that in a real application it would be far better to use propertiesto have access to the Point object's x and y members, instead of making the members public. In addition, it would also be better to use the foreach statement in the DrawLine method instead of a for loop. However, I haven't presented these features of the language yet. I'll cover properties in "Properties, Arrays, and Indexers," and the foreach statement in Chapter 11, "Program Flow Control." -