CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
These methods may be invoked as you would expect:
static void PassAndReceiveArrays()
{
Console.WriteLine("=> Arrays as params and return values.");
// Pass array as parameter.
int[] ages = {20, 22, 23, 0} ;
PrintArray(ages);
// Get array as return value.
string[] strs = GetStringArray();
foreach(string s in strs)
Console.WriteLine(s);
}
Console.WriteLine();
At this point, hopefully you feel comfortable with the process of defining, filling, and examining the
contents of a C# array variable. To complete the picture, let’s now examine the role of the System.Array
class.
The System.Array Base Class
Every array you create gathers much of its functionality from the System.Array class. Using these
common members, you are able to operate on an array using a consistent object model. Table 4-2 gives
a rundown of some of the more interesting members (be sure to check the .NET Framework 4.5 SDK
documentation for full details).
Table 4-2. Select Members of System.Array
Member of Array Class
Meaning in Life
Clear()
This static method sets a range of elements in the array to empty
values (0 for numbers, null for object references, false for booleans).
CopyTo()
This method is used to copy elements from the source array into the
destination array.
Length
This property returns the number of items within the array.
Rank
This property returns the number of dimensions of the current array.
Reverse()
This static method reverses the contents of a one-dimensional array.
Sort()
This static method sorts a one-dimensional array of intrinsic types. If
the elements in the array implement the IComparer interface, you can
also sort your custom types (see Chapter 9).
Let’s see some of these members in action. The following helper method makes use of the static
Reverse() and Clear() methods to pump out information about an array of string types to the console:
138