Notice that the definition of the array’s final row ends with a comma. You don’t
need this comma because nothing follows this last row but C# allows you to
include it to give the rows a more uniform format. The commas after the other
rows are required because more rows follow them.
Array Properties and Methods
All arrays have a Length property that your code can use to determine the number of items in the
array. Arrays all have lower bound 0, and for one-dimensional arrays,
Length – 1 gives an array’s
upper bound.
Arrays also have
GetLowerBound and GetUpperBound methods that return the lower and upper
bounds for a particular dimension in an array.
For example, the following code creates a 5-by-10 array. It then displays the lower and upper bounds
for the first dimension. (The dimension numbers start at 0.)
int[,] x = new int[5, 10];
MessageBox.Show(“The first dimension runs from “ +
x.GetLowerBound(0) + “ to “ + x.GetUpperBound(0));
The Array class also provides several useful static methods that you can use to manipulate arrays.
For example, the following code sorts the array named
salaries:
Array.Sort(salaries);
To sort an array, the array must contain things that can be compared in a mean-
ingful way. For example,
int and string data have a natural order, so it’s easy
to say that the string “Jackson” should come before the string “Utah.”
If an array holds Employee objects, however, it’s unclear how you would want to
compare two items. In fact, it’s likely that you couldn’t define an order that would
always work because sometimes you might want to sort employees by name and
other times you might want to sort them by employee ID or even salary.
You can solve this problem in a couple of ways including the
IComparer inter-
face (mentioned briefly in Lesson 27’s Exercise 2) and making the
Employee
class implement
IComparable (mentioned in Lesson 28). These are slightly more
advanced topics, so they aren’t covered in great depth here.
The Sort method has many overloaded versions that perform different kinds of sorting. For example,
instead of passing it a single array you can pass it an array of keys and an array of items. In that case the
method sorts the keys, moving the items so they remain matched up with their corresponding keys.
The Table 16-1 summarizes the most useful methods provided by the
Array class.
596906book.indd 199 4/8/10 7:40:03 AM