Core C# and .NET

 < Day Day Up > 

C#, like most programming languages, provides the array data structure as a way to collect and manipulate values of the same type. Unlike other languages, C# provides three types of arrays. One is implemented as an ArrayList object; another as a generic List object; and a third is derived from the System.Array class. The latter, which is discussed here, has the traditional characteristics most programmers associate with an array. The ArrayList is a more flexible object that includes special methods to insert and delete elements as well as dynamically resize itself. The List is a type-safe version of the ArrayList that was introduced with .NET 2.0 and may eventually replace the ArrayList. The List and ArrayList are discussed in Chapter 4, along with other Collection classes.

Before looking at the details of creating and using an array, you should be familiar with its general features:

  • Each element in the array is of the type specified in the array declaration. Besides the usual primitive types, an array may contain structures, objects, enums, and even other arrays.

  • Common Language Specification (CLS) compliance requires that all arrays be zero-based to ensure language interoperability (for example, an array reference in C# can be passed to code written in VB.NET). Although it is possible to create a non-zero based array in C#, it is discouraged because array operations are optimized for zero-based dimensions.

  • When an array is created, it is allocated space for a fixed number of elements. Its capacity cannot be dynamically increased. The ArrayList/List is usually a better choice when the number of elements the array must hold is unknown.

Declaring and Creating an Array

Syntax:

<type> identifier [ ] = new <type> [n] [{ initializer list}]

Example:

int[] myRating; // declares an array myRating = new int[5]; // creates array and allocates memory int[] myRating = new int[5] {3,4,7,2,8}; int[] myRating = {3,4,7,2,8}; // shorthand version // Create array containing instances of an Apparel class. Apparel myApparel = {new Apparel(), new Apparel(), new Apparel()); // Set to an enum Fabric[] enumArray = new Fabric[2]; enumArray[0] = Fabric.Cotton; // Create a 2-dimensional array with 3 rows and 2 columns int[ , ] myRatings = {{3 , 7}, {4 , 9}, {2, 6}};

The size of the array is determined from the explicit dimensions or the number of elements in the optional initializer list. If a dimension and an initializer list are both included, the number of elements in the list must match the dimension(s). If no initialization values are specified, the array elements are initialized to 0 for numeric types or null for all others. The CLR enforces bounds checking any attempt to reference an array index outside its dimensions results in an exception.

Using System.Array Methods and Properties

The System.Array class defines a number of properties and methods that are used to query an array and manipulate its contents. Array operations include sorting, copying, searching for specific values, and clearing the contents. Table 2-10 summarizes some of the more useful members of the System.Array class.

Table 2-10. Selected Members of System.Array

Member

Type

Description

Length

Instance property

Total number of elements in the array.

Rank

Instance property

Number of dimensions of the array.

CreateInstance

Static method

Creates an Array object.

To create a single-dimensional array:

int[] rank1 = (int[]) Array.CreateInstance(typeof(int),4);

GetUpperBound(n)

Instance method

The upper bound of a specified dimension n. Returned value is Length 1.

d0 = myArray.GetUpperBound(0); d1= myArray.GetUpperBound(1);

Sort

Static method

Sorts the elements in an array or a section of an array.

Reverse

Static method

Reverses the elements in a one-dimensional array.

IndexOf, LastIndexOf

Static method

Returns the index of the first or last occurrence of a value in a one-dimensional array.

Clone

Instance method

Copies the contents of an array into a new array. The new array is a shallow copy of the original that is, reference pointers, not values, are copied.

Copy

Static method

Copies a selected portion of one array to another.

Clear

Static method

Sets a specified range of elements in an array to zero or null.

The members are classified as static or instance. A static member is not associated with any particular array. It operates as a built-in function that takes any array as a parameter. The instance members, on the other hand, are associated with a specific instance of an array. The example shown in Listing 2-3 demonstrates how to use many of these class members.

Listing 2-3. Working with Arrays Using System.Array Members

class MyApp { static void Main() { string[] artists = {"Rembrandt", "Velazquez", "Botticelli", "Goya", "Manet","El Greco"}; // ..Sort array in ascending order Array.Sort(artists); // ..Invert the array Array.Reverse(artists); PrintArray(artists); // call method to list array int ndx = Array.IndexOf(artists,"Goya"); // ndx = 3 // ..Clone the array string[] artClone = (string[]) artists.Clone(); // Do arrays point to same address? bool eq = Object.ReferenceEquals( artClone[0],artists[0]); // true Array.Clear(artClone,0,artClone.Length); // ..Copy selected members of artists to artClone Array.Copy(artists,1,artClone,0,4); eq = Object.ReferenceEquals( artClone[0],artists[1]); // true } // List contents of Array public static void PrintArray(string[] strArray) { for ( int i = 0; i<= strArray.GetUpperBound(0); i++ ) { Console.WriteLine(strArray[i]); } } }

Things to note:

  • The Sort method has many overloaded forms. The simplest takes a single-dimensional array as a parameter and sorts it in place. Other forms permit arrays to be sorted using an interface defined by the programmer. This topic is examined in Chapter 4.

  • The Clone method creates a copy of the artists array and assigns it to artClone. The cast (string[]) is required, because Clone returns an Object type. The Object.ReferenceEquals method is used to determine if the cloned array points to the same address as the original. Because string is a reference type, the clone merely copies pointers to the original array contents, rather than copying the contents. If the arrays had been value types, the actual contents would have been copied, and ReferenceEquals would have returned false.

  • The Copy method copies a range of elements from one array to another and performs any casting as required. In this example, it takes the following parameters

    (source, source index, target, target index, # to copy)

     < Day Day Up > 

    Категории