C Sharp

Variable Method Parameters

Sometimes the number of arguments that will be passed to a method won't be known until run time. For example, say you wanted a class that would plot a line on a graph according to a series of x-coordinates and y-coordinates. You could have the class expose a method that would take as its only argument a single Point object representing both an x value and a y value. This method would then store each Point object in a linked list or array member until the caller wanted to print out the entire sequence of points. However, this is a poor design decision for a couple of reasons. First, it requires the user to perform the unnecessary work of calling one method for each point of the line to be drawn-very tedious if the line will be long-and then calling another method to have the line drawn. The second drawback is that it requires the class to store these points in some fashion when the only reason the points are needed is for the use of a single method, the DrawLine method. Variable arguments work great to solve this sort of problem.

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." -

by BrainBellupdated
Advertisement: