Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. Methods > Variable Method Parameters

Variable Method Parameters

Sometimes you won’t know the number of arguments that you pass to a method until run time. For example, suppose you want a class that plots a line on a graph according to a series of x and y coordinates. You could have the class use a method that takes as its only argument a single Point object representing both an x value and a y value. This method will then store each Point object in a linked list or array member until the caller wants 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 draw (which is very tedious if the line is long) and then calling another method to draw the line. The technique’s second drawback is that it requires the class to somehow store these points even though they’re needed only for a single method, DrawLine.

Variable arguments work well to solve these problems. 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. This example of the Draw class in C# allows the user to make a single call that takes a variable number of Point objects and prints each one:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint