Chapter 11: Understanding Parameter Arrays


Chapter 11

Understanding Parameter Arrays

After completing this chapter, you will be able to:

  • Write a method that can accept any number of arguments by using the params keyword.

  • Write a method that can accept any number of arguments of any type by using the params keyword in combination with the object type.

Parameter arays are useful if you want to write methods that can take variable numbers of arguments, possibly of different types, as parameters. If you are familiar with object-oriented concepts, you might well be grinding your teeth in frustration at this sentence. After all, the object-oriented approach to solving this problem is to define overloaded methods.

Overloading is the technical term for declaring two or more methods with the same name in the same scope. Being able to overload a method is very useful in cases where you want to perform the same action on arguments of different types. The classic example of overloading in Microsoft Visual C# is Console.WriteLine. The WriteLine method is overloaded numerous times so that you can pass any primitive type argument:

class Console {     public static void WriteLine(int parameter)      ...     public static void WriteLine(double parameter)      ...     public static void WriteLine(decimal parameter)      ... }

As useful as overloading is, it doesn't cover every case. In particular, overloading doesn't easily handle a situation in which the type of parameters doesn't vary, but the number of parameters does. For example, what if you want to write many values to the console? Do you have to provide versions of Console.WriteLine that can take two parameters, other versions that can take three parameters, and so on? That would quickly get tedious. And doesn't the massive duplication of all these overloaded methods worry you? It should. Fortunately, there is a way to write one method that takes a variable number of arguments (a variadic method): You can use a parameter array (a parameter declared with a params keyword).

To understand how params arrays help to solve this problem, it helps to first understand the uses and shortcomings of plain arrays.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net