Free mag vol1 | Page 192

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II // ...or pass an array of doubles. double[] data = { 4.0, 3.2, 5.7 }; average = CalculateAverage(data); Console.WriteLine("Average of data is: {0}", average); // Average of 0 is 0! Console.WriteLine("Average of data is: {0}", CalculateAverage()); Console.ReadLine(); } If you did not make use of the params modifier in the definition of CalculateAverage(), the first invocation of this method would result in a compiler error, as the compiler would be looking for a version of CalculateAverage() that took five double arguments.  Note To avoid any ambiguity, C# demands a method only support single params argument, which must be the final argument in the parameter list. As you might guess, this technique is nothing more than a convenience for the caller, given that the array is created by the CLR as necessary. By the time the array is within the scope of the method being called, you are able to treat it as a full-blown .NET array that contains all the functionality of the System.Array base class library type. Consider the following output: You sent me 5 doubles. Average of data is: 32.864 You sent me 3 doubles. Average of data is: 4.3 You sent me 0 doubles. Average of data is: 0 Defining Optional Parameters C# allows you to create methods that can take optional arguments. This technique allows the caller to invoke a single method while omitting arguments deemed unnecessary, provided the caller is happy with the specified defaults.  Note As you will see in Chapter 16, a key motivation for adding optional arguments to C# is to simplify interacting with COM objects. Several Microsoft object models (e.g., Microsoft Office) expose their functionality via COM objects, many of which were written long ago to make use of optional parameters, which earlier versions of C# did not support. 127