Declaring and Defining an Array

   


In certain respects, the array is very similar to the string type, which, for that reason, is often referred to as an array of characters. I expect you to be reasonably familiar with the string class by now and I will briefly use it here to familiarize you with the array concept.

Recall how a variable of type string is able to hold a collection of characters, all neatly ordered and indexed, facilitating easy access to each character as in


graphics/10infig01.gif

which assigns the letter i to ch. Or as in


graphics/10infig02.gif

which counts the number of bs in myText and generates the following output:

 Number of b's in text: 3 

Notice that myText is the only name needed to access any of the individual characters in the collection of characters it represents, as long as we combine it with an index enclosed by square brackets. This uniform compact method of referencing individual characters, as you will see shortly, is identical to that of referencing individual data elements in an array.

The string and array are both class types and reference types. Whereas the underlying class for the string type is the .NET class System.String, an array originates from the System.Array class. Consequently, an array is an object, which, like the string object, has many built-in methods useful for accessing and manipulating collections of data items.

There are many similarities between strings and arrays, but, while the string type along with its built-in methods is specialized in and restricted to represent collections of characters, an array can be declared to hold a collection of any type of values, including any of the simple types int, long, decimal and so on, and any group of objects, such as elevators, persons, strings, Blipos Clocks, and so on.

An array is a named data structure (or object) that maps a list of index numbers with a collection of data storage locations called array elements. All array elements must be of the same type. The type of the array elements is called the array element type, also referred to as the base type of the array.

Array elements are sometimes called indexed variables, subscripted variables, or simply elements.

A variable of type array is declared in the source code by specifying the array element type followed by an empty pair of square brackets and the name of the array. The following line of source code

 decimal [] accountBalances; 

declares a variable of the name accountBalances with the ability to hold a reference to an array object containing a collection of decimal numbers. The only syntactical difference between declaring a single variable of, say, decimal and an array variable of base type decimal is the pair of square brackets.

Note

graphics/common.gif

Sometimes, programmers position the square brackets immediately next to the type name as in the following

 decimal[]  accountBalances; 

to highlight the notion of an array. Whichever style you choose, remember to be consistent.


The previous declaration merely creates an empty container with the ability to hold a reference to an array object. The array object itself, with its collection of decimal values, is not yet created, and no memory has so far been allocated for this purpose.

An object of type array, must, like any other class (with the exception of strings), be created by applying the keyword new, which you have used before to create Elevator and Person objects. The single line of code in Figure 10.1 instantiates an array object (of class System.Array) that will hold a collection of five decimal values and assigns its reference to accountBalances.

Figure 10.1. Creating an array object of five elements.
graphics/10fig01.gif

The name of a valid type, such as int or as in this case decimal must follow the new keyword. A pair of square brackets enclosing an integer number, specifying the number of array elements in the array object created, follows. This number must be implicitly convertible to type int. As usual, a semicolon terminates the whole statement.

Note

graphics/common.gif

Instead of separating the declaration statement from the instantiation statement into two lines, it is possible to combine them in the same line, as follows:

 decimal [] accountBalances = new decimal [5]; 


Note

graphics/common.gif

You might encounter a syntax significantly different from that already shown to declare array variables and create new array objects. This syntax refers to the class and method names from the .NET Framework directly in the source code, as demonstrated in the following line

 System.Array rainfall = System.Array.CreateInstance( Type.GetType ("System.Decimal"), 5 ); 

that declares an array variable called rainfall and assigns it a reference to a new array object of base type decimal. The syntax shown in this Note is not applied in this book, but merely presented so you can recognize it if you stumble upon it in source code written by other programmers.


After the array variable accountBalances has been declared and assigned a new array object, the state of affairs can be illustrated, as in Figure 10.2. accountBalances now contains a reference pointing to a specific object of class System.Array located somewhere in the computer memory. This object has the capacity to hold a collection of five decimal values. Because each decimal takes up 128 bits (or 16 bytes), this part of the array object will occupy 5 x 128 bits = 640 bits (or 80 bytes). The reference itself takes up 4 bytes of memory.

Figure 10.2. Array variable referencing array object.
graphics/10fig02.gif

An array length is the total number of array elements an array can hold. Another term used instead of length is size.

It is possible, as you will see shortly, to specify and assign initial values to elements of the array at the same time as it is being created. When an array is created without any initial values, as in the previous examples, its array elements are automatically assigned default values. The default values vary according to the array element type:

  • Numerical values of type short, int, float, decimal and so on are assigned the value zero.

  • Values of type char are assigned the Unicode character \u0000.

  • Values of type bool are initialized to the value false.

  • Values of reference types are initialized to null.

In our example, the array element type is decimal, so all values are initialized to zero, as indicated in Figure 10.2. It is generally a good idea to perform your own initializations in the source code rather than relying on default values provided by the compiler. Not only does it make the code clearer for programmers who are not up to date with the particular default values provided, it also prevents the program from being susceptible to default values that might change over time or differ between various compilers from different compiler makers.

The null Value

graphics/bulb.gif

When a reference is not referencing any particular object, it references the null object. null is compatible with all reference types. It is represented by the keyword null in C#. If you want a reference to point to nothing, you can assign it the value null as in the following:

 elevator3 = null; 


The general syntax for declaring and creating a single array is shown in Syntax Box 10.1.

Syntax Box 10.1 Single array declaration and instantiation

 Array_declaration::= <Base_type> [] <Array_identifier>; Array_creation::= new <Base_type> [<Array_length>] Array_reference_assignment::= <Array_identifier> = new <Base_type> graphics/ccc.gif [<Array_length>];                           ::= <Array_declaration> = new <Base_type> graphics/ccc.gif [<Array_length>]; 

Notes:

  • The <Base_type> of the declaration must be identical to the <Base_type> of the instantiation.

  • <Array_length> must be positive and of a type implicitly convertible to type int. It can be a literal, constant, or variable.

  • The square brackets [] do not indicate an option in this case (otherwise they would have been printed as [] ); the square brackets must be written as part of the syntax.

When the array has been declared and a reference to an array object assigned, we are ready to access its individual array elements.


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net