CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
Note The C# ref keyword will be revisited later in this chapter in the section “Understanding Value Types and
Reference Types.” As you will see, the behavior of this keyword changes just a bit depending on whether the
argument is a value type or reference type.
The params Modifier
C# supports the use of parameter arrays using the params keyword. To understand this language feature,
you must (as the name implies) understand how to manipulate C# arrays. If this is not the case, you
might wish to return to this section after you read the section “Array Manipulation in C#,” later in this
chapter.
The params keyword allows you to pass into a method a variable number of identically typed
parameters (or classes related by inheritance) as a single logical parameter. As well, arguments marked
with the params keyword can be processed if the caller sends in a strongly typed array or a commadelimited list of items. Yes, this can be confusing! To clear things up, assume you wish to create a
function that allows the caller to pass in any number of arguments and return the calculated average.
If you were to prototype this method to take an array of doubles, this would force the caller to first
define the array, then fill the array, and finally pass it into the method. However, if you define
CalculateAverage() to take a params of double[] data types, the caller can simply pass a commadelimited list of doubles. The .NET runtime will automatically package the set of doubles into an array of
type double behind the scenes:
// Return average of "some number" of doubles.
static double CalculateAverage(params double[] values)
{
Console.WriteLine("You sent me {0} doubles.", values.Length);
double sum = 0;
if(values.Length == 0)
return sum;
}
for (int i = 0; i < values.Length; i++)
sum += values[i];
return (sum / values.Length);
This method has been defined to take a parameter array of doubles. What this method is in fact
saying is, “Send me any number of doubles (including zero) and I’ll compute the average.” Given this,
you can call CalculateAverage() in any of the following ways:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
...
// Pass in a comma-delimited list of doubles...
double average;
average = CalculateAverage(4.0, 3.2, 5.7, 64.22, 87.2);
Console.WriteLine("Average of data is: {0}", average);
126