8.1. What is an Array?

An array is a group of identical data types that share a common name. The syntax for defining an array is as follows:

typeSpecifier[] arrayName = new typeSpecifier[numberOfElements];

where

  • typeSpecifier is the data type you want to use,

  • arrayName is the name you wish to use for the array, and

  • numberOfElements is the number of array elements you want.

Each of these parts is explained in a moment using the following example.

Suppose you have an address book with 100 names in it. Because you want to manipulate those names in some way in your program, each name must be stored in a variable. Because names are textual data, you could use something like this:

string name00;
string name01;
string name02;
string name03;
//. . . Many more variables. . .
string name98;
string name99;

While this would work, it suffers two serious drawbacks. First, you would get really tired of typing in all those variable names. Even worse, think what would happen if the address book had a million names in it! Second, how would you perform the common task of searching the names in the list for a specific person? You'd be forced to plow through 100 if statements looking for a particular name:

if (name00.Equals(targetName))
{
    index = 0;
}
else
{
     if (name01.Equals(targetName))
     {
          index = 1;
     }
else   //. . . and so on. . .

(Remember that when you compare objects like strings, you don't compare rvalue-to-rvalue. Instead, you want to compare what is stored at the memory address contained in the ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.