Advertisment

C# Arrays

author-image
PCQ Bureau
New Update

Arrays in C# have changed a lot from their traditional counterparts. Here, we define arrays, move on to single dimensional arrays, and do multidimensional arrays and their kinds next month.

Advertisment

What are Arrays?

An array is a contiguous location in memory that can hold identical type of data, that is, either all integers, or all longs, etc. From our knowledge of CTS,we know that arrays are reference types.

Single-dimensional arrays

Advertisment

We declare an array of the type integer as:

int <> a;

This declares a to be an array reference variable of the type integer, that is single dimensional in nature. 

Advertisment

int <> first, second;

This declares first and second as array variables. These statements only declare the array, they don’t construct it. To do so, we use the new operator as follows:

int <> first;



first = new int<10>;

Advertisment

The first line declares the array variable. The second line defines the variable first to be referencing the memory location, which can contain ten integer values. When defining the array size, the size once specified remains fixed throughout. Now, onto accessing the array elements. The above-declared array, referenced by first, would be present in memory like this:

first

                        
Advertisment
0 1 2 3 4 5 6 7 8 9

Ten memory locations are divided into equal number of array compartments. To access each of these, we use an index number that lies in the range of 0 to N-1, where N is the total number of elements the array can contain, and is specified during its creation. Hence, the elements of the array referenced by first are indexed from 0 to 9, totaling ten elements in all. Accessing elements outside the valid range will result in a runtime exception. To assign values to the elements once an array has been created, we assign the value to the corresponding array compartment:

first<0>=1;



first<3>=2;

Advertisment

While the first line assigns a value of 1 to the first array compartment, the second line assigns the value of 2 to the fourth array compartment. Remember that arrays are zero based. Thus, the fourth compartment would be referenced using the index number of 3. To initialize the array with a set of values:

int <> first = new int {2,3,5,7};





or




int <> first = {2,3,5,7};

Here, first is automatically sized by the compiler and in this case, the size of the array is four, since that’s the number of elements the array is initialized to. Also, the first compartment of the referenced array is assigned the value 2, the second compartment is assigned the value 3, and so on.

We will discuss multidimensional arrays in detail next month, but you’ll find the source code to start off with C# arrays on the CD with this issue. 

Kumar Gaurav Khanna

Advertisment